简体   繁体   中英

How to get a number entered by the user to exit a loop?

I'm trying to get the user to input any number between 0 and 10 an unlimited amount of times until they want to stop. They stop by entering the value -1. So far i have been able to create what happens when they enter a correct value, but when they enter -1 (which is an invalid value in the while loop), the program knows that it's invalid. All I'm looking for is for the program to exclude -1 for the possible invalid input, and to make the program stop asking for more input. Here's my code so far:

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

Sorry for my limited understanding :/

I would suggest that you're trying to do too much with while loops. As it's written, you never get out of your first one. If you enter a number between 0 and 10, it goes back and asks again. If you put anything other than that, you hit that nested while loop and it ends up asking for a number again. Think about the flow and what you want it to do. Here's a quick outline of one way to go at it:

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

At least I think it gets there. There are various methods to control the flow of your code. It's good to know when to use which one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM