[英]Scope of variable outside 'if' loop in main method in a class - unavailable issue
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. 但是,在
if
语句之外,我无法访问numberOfArchersToBeTrained
和numberOfBarbariansToBeTrained
变量。 What am I doing wrong here? 我在这里做错了什么?
The last System.out.println
is not working as the variable numberOfArchersToBeTrained
is not available here 由于变量
numberOfArchersToBeTrained
在此处不可用,因此最后一个System.out.println
不起作用
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,则需要给此变量值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.