Home > Net >  Why does it take additional input for scanner to see an empty line?
Why does it take additional input for scanner to see an empty line?

Time:04-04

public class Test1 {
   public static void main(String[] args) {
      System.out.println("Give me a word: ");
      Scanner console = new Scanner(System.in);
      ArrayList<String> arr = new ArrayList<>();
      boolean found = true;
      
      while (console.hasNextLine() && found) {
         String line = console.nextLine();
         
         if (line.equals("")) {
            found = false;
         } else {
            arr.add(line);
         }
      }
     
      System.out.println("You said: ");
      
      for (int index = 0; index < arr.size(); index  ) {
         System.out.println(arr.get(index)); 
      } 
   }
}

I'd like to print what user typed in whenever the user types enter twice, however this requires three enters to be inputted for some reason. When I remove the console.hasNextLine statement in while loop's condition, it works perfectly fine. Why is this the case?

CodePudding user response:

console.hasNextLine() blocks application flow and waits for input to be received.

1st enter - word is found and found remains == true

2nd enter - word is not found and found is set to == false

3rd enter - is required because your booleans are evaluated in order which they are arranged. so first it'll call console.hasNextLine() and allow user to provide input. THEN it'll check if found == true/false which would == false and would break out of the loop.

an easy solution would be to rearrange your conditions to be

found  && console.hasNextLine()
  • Related