mercredi 15 novembre 2017

How do I reference an object if it is only declared inside of an if statement?

I am trying to call an object, yet I can't because I am using an if statement to declare the object... help?

I am trying to make two robots fight, and it was easiest for me to display the robots using objects and a toString() method. After doing this though, it was difficult to make the two robots fight because I couldn't determine which robots I was using, the only way I could figure out was to make two new robot objects but in order to determine the correct robot stats, I needed to use a new object.

Here is my code:

import javax.swing.JOptionPane;

public class RobotDriver
{                                              //armor health regen damage critical missile        

public static void main(String[] args)
{
Robot Annihilator = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20,    .5);
Robot Gladiator = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
Robot Deadshot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
Robot Tank = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);

String robot1 = "";
String robot2 = "";

String Robot1 = JOptionPane.showInputDialog(Annihilator + "\n" + Gladiator + "\n" + Deadshot + "\n" + Tank + "Choose First Robot: ");


String Robot2 = JOptionPane.showInputDialog(Annihilator + "\n" + Gladiator + "\n" + Deadshot + "\n" + Tank + "Choose Second Robot: ");


System.out.println("Robot #1: " + Robot1 + "\n\nRobot #2: " + Robot2);


if(Robot1.equals(Annihilator.getName()))
{
Robot firstRobot = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20, .5);
}
if(Robot1.equals(Gladiator.getName()))
{
Robot firstRobot = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
}
if(Robot1.equals(Deadshot.getName()))
{
Robot firstRobot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
}
if(Robot1.equals(Tank.getName()))
{
Robot firstRobot = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);
}



if(Robot2.equals(Annihilator.getName()))
{
Robot secondRobot = new Robot("Annihilator", 22.88, 524.4, 2.34, 53.66, .20, .5);
}
if(Robot2.equals(Gladiator.getName()))
{
Robot secondRobot = new Robot("Gladiator", 25, 467.3, 1.23, 58, .25, .10);
}
if(Robot2.equals(Deadshot.getName()))
{
Robot secondRobot = new Robot("Deadshot", 10, 325.9, 0, 55, .80, .15);
}
if(Robot2.equals(Tank.getName()))
{
Robot secondRobot = new Robot("Tank", 45, 1300, 0, 24.9, .2, 0);
}



boolean fight = true;


while(fight)
{
   //this is where the error occurs because the objects aren't declared
   fight(firstRobot, secondRobot);

}

Aucun commentaire:

Enregistrer un commentaire