0

I looked over previous posts and still cannot understand the root of what's going on here with the "consume line" concept. Can someone explain, slowly and step by step, what the program is reading/doing that skips over the string input

below is the code:

import java.util.Scanner; public class consumeScannerNextLine {

public static void main (String args []){

    Scanner key = new Scanner(System.in);

    System.out.println("number1: ");
    int num1 = key.nextInt(); 

    System.out.println("number2: ");
    String num2 = key.nextLine(); 

    System.out.println("number3: ");
    int num3 = key.nextInt(); 

    System.out.println("");
    System.out.println("");

    System.out.println(num1 + "  One");
    System.out.println(num2 + "  Two");
    System.out.println(num3 + "  Three");



}

}

Output:

number1:

10

number2: number3:

10

10 One Two 10 Three

so I read over the other posts below as suggested and found one of the answers to be helpful but still not clear.

"It's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". When input.nextLine() executes, it consumes the "end of line" still in the buffer from the first input.

Instead, use input.nextLine() immediately after input.nextInt()"

My question is that what does it mean by consume end of the line? If it consumes the end of the line, what does that have to do with skipping a new input such as the string? That seems like a big flaw in java

Furthermore, then what exactly does the statement
System.out.println("number2: "); String num2 = key.nextLine(); do? What is it stored in the string variable num2 and what happens before/after?

Borla312
  • 55
  • 4
  • 2
    Check [Skipping nextLine() after using next(), nextInt() or other nextFoo() methods](http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods) – sam Oct 18 '15 at 17:50
  • 1
    I read over the link and found this answer to be useful: "It's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". When input.nextLine() executes, it consumes the "end of line" still in the buffer from the first input. Instead, use input.nextLine() immediately after input.nextInt()" however, I still don't understand what it consumes. How can you consume end of the line? And what does that have to do with skipping the next input? – Borla312 Oct 18 '15 at 18:19
  • The end of each line of input is marked by one or more literal, readable characters, normally either a newline or a carriage-return / newline pair. This line terminator, and and run of space and/or tab characters preceding it, is what can be left unread after you read and consume a token. – John Bollinger Oct 18 '15 at 20:08

0 Answers0