我想保存弓箭手和野蛮人的价值。但是,在if语句之外,我无法访问numberOfArchersToBeTrained和numberOfBarbariansToBeTrained变量。我在这里做错什么了?
最后一个System.out.println无法工作,因为变量numberOfArchersToBeTrained在这里不可用。
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();
}
}发布于 2015-12-18 19:54:21
如果预围栏为2或3,则未初始化numberOfArchersToBeTrained,则需要给出此变量值。
发布于 2015-12-18 19:44:47
初始化numberOfArchersToBeTrained在开始时,您的代码正在工作;
int numberOfArchersToBeTrained = 0;https://stackoverflow.com/questions/34362781
复制相似问题