Home > front end >  Java do-while loop not Scanning user input
Java do-while loop not Scanning user input

Time:10-11

I want to do a Do-While loop with user input while the input is less than 100 but my IDE won't accept it the way eventhough i guess it is the way a Do-While loop looks like.

int counter = 0;
        do {
            Scanner input = new Scanner(System.in);
            int i = input.nextInt();
            counter   ;
            System.out.println("Number "   counter   input.nextInt());

        }
        while (i < 100);

CodePudding user response:

You are creating a completely new Scanner object, each of which tries to read input independently, inside each iteration of your loop, and as @Jens pointed out, you're consuming the input twice. Instead,

int counter = 0;
int i;
Scanner input = new Scanner(System.in);

do {
  i = input.nextInt();
  // now use i, don't call nextInt() again
} while { i < 100 }; // and you should usually use `input.hasNextInt()`

CodePudding user response:

i needs to be defined outside the loop.

  • Related