gpt4 book ai didi

java - 类中主方法中 'if' 循环之外的变量范围 - 不可用问题

转载 作者:行者123 更新时间:2023-11-30 03:07:34 25 4
gpt4 key购买 nike

我想存储弓箭手和野蛮人的值(value)。但是,在 if 语句之外,我无法访问 numberOfArchersToBeTrainednumberOfBarbariansToBeTrained 变量。我在这里做错了什么?

最后一个 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();
}
}

最佳答案

如果 prefence 为 2 或 3,numberOfArchersToBeTrained 未初始化,您需要为此变量指定值

关于java - 类中主方法中 'if' 循环之外的变量范围 - 不可用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com