How would I use a while loop to keep requesting user input

前端 未结 3 1174
日久生厌
日久生厌 2021-01-17 04:50

I\'ve tried a couple of things with the while loop and can\'t seem to get it to work. I want to keep requesting user input until the user inputs the number 0, here is the co

3条回答
  •  無奈伤痛
    2021-01-17 05:42

    You need to do something to keep you input loop running until a stopping condition is encountered (which in your case is that when the user inputs 0)

    // First get the scanner object with the input stream
    Scanner sc = new Scanner(System.in); 
    
    // Just using do-while here for no reason, you can use a simple while(true) as well
    do{
        int input = sc.nextInt();  // read the next input
        if (int == 0) { // check if we need to exit out
            // break only if 0 is entered, this means we don't want to run the loop anymore
            break;
        } else {
            // otherwise, do something with the input
        }
    } while(true); // and keep repeating
    

提交回复
热议问题