0

I'm new to Java and still confused on how the scanner next methods actually work. I have an example program right here:

import java.util.Scanner;

public class HelloJava{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int varInt;
        String varString;
        String varStringTwo;

        System.out.print("Insert int value: ");
        varInt = sc.nextInt();
        System.out.print("Insert string value: ");
        varString = sc.nextLine();
        System.out.print("Insert another string value: ");
        varStringTwo = sc.nextLine();

        sc.close();
    }
}

When i executed the program and entered an integer on the first prompt, the terminal looked like this:

Insert int value: 15
Insert string value: Insert another string value: // i can input any value here //
//                  ^ but the program doesn't allow me to input anything here

I know that one of the solution is to put "sc.nextLine();" between varInt = "sc.nextInt();" and "System.out.print("Insert a string value: ");", but I don't understand why or how.

  • 1
    Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Masterhaend Mar 01 '21 at 15:33
  • It seems you already figured the solution to that problem, but well: most answers here and elsewhere **explain** what that is. – GhostCat Mar 01 '21 at 15:34

1 Answers1

0

When you scan a String values with spaces the scanner.next() method will get you the string up to space.

For example,

your input is This is a String so when the first time you run scanner.next() it will return the value This. If you run it a second time it will return you is and so on.

iamdhavalparmar
  • 772
  • 3
  • 19
  • 2
    but the important point is that on line end, which is also used a separator, the new line (carriage return) character is not consumed by `nextInt()`, and `nextLine()` only reads up to that new line (consuming it, but returning an empty string). `nextInt()` ignores are leading separators (spaces, new lines, ...) –  Mar 01 '21 at 15:38