-1

这是我的 World.java 中的代码

    while (option == 1)
    {
        a.generate();
        a.count();
        System.out.println("Max number is "+ a.maximum(max));
        System.out.println("Average number is "+ a.average(aver));
        System.out.println("Min number is "+ a.minimum(min));
        System.out.println("Do you want to run it again (y/n)?: ");
        a.getchoice();
    } 
    if (option == 2)
    {
        System.out.println("Program exits.");
        System.exit(0);
    }

这是我的 rg.java 中的代码

    public int getchoice() {
            Scanner reader = new Scanner(System.in);
            String selection = reader.nextLine();
            if(!selection.toLowerCase().equals("y") && !selection.toLowerCase().equals("n"))
            {
                System.out.print("Invalid. Please enter “y” or “n”: ");
                return this.getchoice();
            }
            if (selection.toLowerCase().equals("y")){
                return 1;
            }
            else
            {
                return 2;
            }

我想返回变量以在世界级中运行选项 y/n。

但问题是,如果我在运行程序后按 y,然后出现问题,我按 y 或 n 程序仍然执行,就好像选项是 1。

任何人都可以检查以找出我的代码中的哪一部分出错了吗?对不起这个新代码,因为我刚开始学习java

4

2 回答 2

3

你从来没有设置option

试试这个:

  option = a.getChoice();
于 2013-05-03T15:19:30.497 回答
2

您没有getChoice()在变量中捕获方法的结果option。所以while循环永远不会终止。

改成

while (option == 1)
{
    a.generate();
    a.count();
    System.out.println("Max number is "+ a.maximum(max));
    System.out.println("Average number is "+ a.average(aver));
    System.out.println("Min number is "+ a.minimum(min));
    System.out.println("Do you want to run it again (y/n)?: ");
    option = a.getchoice();
} 
于 2013-05-03T15:20:58.413 回答