[英]Scope of variable outside 'if' loop in main method in a class - unavailable issue
我想存儲弓箭手和野蠻人的價值。 但是,在if
語句之外,我無法訪問numberOfArchersToBeTrained
和numberOfBarbariansToBeTrained
變量。 我在這里做錯了什么?
由於變量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.