I want to store the value of Archers and Barbarians. However, outside the if
statement I cannot get access to the numberOfArchersToBeTrained
and numberOfBarbariansToBeTrained
variables. What am I doing wrong here?
The last System.out.println
is not working as the variable numberOfArchersToBeTrained
is not available here
public class ConsoleInteraction {
/**
* @param args
*/
public static void main(String[] args) {
// Create a scanner so we can read the command-line input
Scanner scanner = new Scanner(System.in);
// Prompt for training or viewing camp
System.out.print("What do you want to do: \n 1.Train Troops \n 2. View Troop Camp \n ");
//Get the preference as an integer
int preference = scanner.nextInt();
int numberOfArchersToBeTrained;
int numberOfBarbariansToBeTrained;
//Show options based on preference
if(preference == 1)
{
System.out.println("Whom do you want to train?\n 1.Archer \n 2.Barbarian \n 3.Mix \n Enter You preference:");
int trooppreference = scanner.nextInt();
if (trooppreference == 1)
{
System.out.println("How many Archers you want to train ? : ");
numberOfArchersToBeTrained = scanner.nextInt();
}
else if (trooppreference == 2)
{
System.out.println("How many Barbarians you want to train ? : ");
numberOfBarbariansToBeTrained = scanner.nextInt();
}
else if (trooppreference == 3)
{
System.out.println("How many Archers you want to train ? :");
numberOfArchersToBeTrained = scanner.nextInt();
System.out.println("How many Barbarians you want to train :");
numberOfBarbariansToBeTrained = scanner.nextInt();
}
else
{
System.out.println("You have to select option 1, 2 or 3");
}
}
else if (preference == 2)
{
System.out.println("Showing Camp to You");
}
else
{
System.out.println("You can enter only option 1 or 2");
}
System.out.println("Archers:"+ numberOfArchersToBeTrained);
scanner.close();
}
}
在开始时初始化numberOfArchersToBeTrained
,您的代码正在运行;
int numberOfArchersToBeTrained = 0;
如果偏好是2或3,则没有初始化numberOfArchersToBeTrained,则需要给此变量值
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.