为什么我的代码部分似乎被跳过了?

时间:2017-04-14 22:49:16

标签: java nested-loops

我正在制作一个JAVA程序。它使用递归来根据输入的数量进行计数。我正在使用while循环,如果抛出错误则循环。我试图编写一个功能,允许用户连续输入数字,直到用do / while循环输入n / N.到目前为止,这是我的代码:

public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);

    System.out.print("Enter a number: ");
    String input;
    input = keyboard.nextLine();        
    String again;
    do{
        while(true){
            try{
                int number = Integer.parseInt(input);
                int base = 1;
                /*
                  The countUp function is called from
                  from my parent class SimpleRecursion.java
                  which is where the recursion happens
                */
                countUp(base, number); 
                break;                
            }

            catch(NumberFormatException e){
                System.out.print("Error invalid entry." + "\n" + "Enter a number: ");
                input = keyboard.nextLine();
                continue;
            }
        }

        System.out.print("Again? y or n? ");
        again = keyboard.nextLine();
        if(again.equals("n") || again.equals("N"))
            System.exit(0);
    }while(again.equals("y") || again.equals("Y"));
}

然而,当try块突然出现while循环时,似乎结束了程序。我尝试标记我的do循环A和while循环B并使用"中断B",以打破while循环,但这也不起作用。 另外:我的扫描仪导入位于父类的顶部。我可以发布整个文件,代码可以正常输入一个正确的输入,如果抛出NumberFormatException,程序将正确循环。感谢。

编辑:我再次改变==" string"到again.equals(" string"),结果是一样的。

问题出在我的countUp函数中,如下所示:

public static void countUp(int x, int end){
    if(x > end)
        System.exit(0); // When the number reaches the number entered. The 
                        // program ended. 
    else{
        System.out.print(x + "\n");
        countUp((x+1), end);
    }
}

0 个答案:

没有答案