0

我试图让用户无限次输入 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.");
    }

对不起,我的理解有限:/

4

1 回答 1

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.");
    }
}

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

于 2015-11-07T01:30:30.877 回答