Search code examples
javaloopswhile-loopuser-input

while loop incrementing an extra time


The below while loop runs an extra time. I am trying to perform a user input that accepts 10 valid numbers from the user and prints their sum. However, the while loop executes an extra time and asks for the 11th input.

 import java.util.Scanner;
 class userInput{
 public static void main(String[] args) {
    
    int i = 1, sum = 0;
    Scanner sc = new Scanner(System.in);

    while(i <= 10){
    i++;
    
    System.out.println("Enter number " + "#" +i);
    boolean isValidNumber = sc.hasNextInt();

    if(isValidNumber){
        int userChoiceNumber = sc.nextInt();
        sum += userChoiceNumber;
    }else{
        System.out.println("Invalid Input");
    }
   }
   System.out.println("The sum of your entered numbers are = " + sum);

} }


Solution

  • In addition to those great comments, you should probably only increment "i" if you get a VALID input:

    while(i <= 10) {
      System.out.print("Enter number " + "#" +i + ": ");
      boolean isValidNumber = sc.hasNextInt();
      if(isValidNumber){
        int userChoiceNumber = sc.nextInt();
        sum += userChoiceNumber;
        i++;
      }else{
        System.out.println("Invalid Input");
        sc.next();
      }
    }
    

    Note that when you have a bad input you need to get rid of it with "sc.next()".