如何获取用户输入的数字以退出循环?

时间:2015-11-07 01:02:26

标签: java while-loop exit negative-integer

我试图让用户在0到10之间无限次地输入任何数字,直到他们想要停止。他们通过输入值-1来停止。到目前为止,我已经能够创建输入正确值时发生的事情,但是当它们输入-1(这是while循环中的无效值)时,程序知道它是无效的。我正在寻找的是程序为可能的无效输入排除-1,并使程序停止要求更多输入。到目前为止,这是我的代码:

    int userInput=0;
    System.out.println("Please enter numbers ranging from 0 to 10 (all inclusive).");
    System.out.println("When you want to stop, type and enter -1.");


    while (userInput <= 10 && userInput >= 0)
    {
        userInput=Integer.parseInt(br.readLine());

        while (userInput > 10|| userInput < 0)
        {
            System.out.println("That number is not in between 0 and 10. Please enter a correct number.");
            userInput=Integer.parseInt(br.readLine());
        }
        sum=sum+userInput;
        freq++;
    }
    while (userInput == -1)
    {
        System.out.println("You have chosen to stop inputing numbers.");
    }

对不起我的理解有限:/

1 个答案:

答案 0 :(得分:0)

我建议您尝试使用while循环执行太多操作。正如它的写作,你永远不会离开你的第一个。如果输入0到10之间的数字,它会返回并再次询问。如果您放置除此之外的任何内容,则会触发嵌套while循环,并最终再次请求数字。想想流程以及您希望它做什么。以下是一种快速概述的方法:

System.out.println("Please enter numbers ranging from 0 to 10 (all inclusive).");
System.out.println("When you want to stop, type and enter -1.");
keepgoing = true;
while(keepgoing) {
    userInput=Integer.parseInt(br.readLine());
    if((userInput <= 10 && userInput >= 0) {
        sum=sum+userInput;
        freq++;
    }
    else if(userInput == -1) {
        System.out.println("You have chosen to stop inputing numbers.");
        keepgoing = false;
    }
    else {
        System.out.println("That number is not in between 0 and 10. Please enter a correct number.");
    }
}

至少我认为它会到达那里。有多种方法可以控制代码的流程。知道何时使用哪一个很好。