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

时间:2015-12-18 19:39:51

标签: java variables

我想存储弓箭手和野蛮人的价值。但是,在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();
    }
}

2 个答案:

答案 0 :(得分:1)

在开头初始化numberOfArchersToBeTrained,您的代码正在运行;

 int numberOfArchersToBeTrained = 0;

答案 1 :(得分:1)

如果prefence为2或3, numberOfArchersToBeTrained 未初始化,则需要提供此变量值