首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在一个类不可用的问题中,main方法中的“if”循环外的变量范围

在一个类不可用的问题中,main方法中的“if”循环外的变量范围
EN

Stack Overflow用户
提问于 2015-12-18 19:39:50
回答 2查看 61关注 0票数 1

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

最后一个System.out.println无法工作,因为变量numberOfArchersToBeTrained在这里不可用。

代码语言:javascript
运行
复制
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();
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-18 19:54:21

如果预围栏为2或3,则未初始化numberOfArchersToBeTrained,则需要给出此变量值。

票数 1
EN

Stack Overflow用户

发布于 2015-12-18 19:44:47

初始化numberOfArchersToBeTrained在开始时,您的代码正在工作;

代码语言:javascript
运行
复制
 int numberOfArchersToBeTrained = 0;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34362781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档