javastringjava.util.scannerdrjava

Scanner for string does not work in Java


When I use scan.nextLine(), input boxes don't work properly. If it's scan.next() ,works perfectly.But Why? Ain't I supposed to use scan.nextLine() for string?

import java.util.Scanner;
public class Test{
public static void main(String[] args){

    Scanner scan = new Scanner(System.in);
    int x = scan.nextInt();
    System.out.println("p");
    String p = scan.nextLine();
    System.out.println("q");
    String q = scan.next();
    System.out.println("m");
    String m = scan.next();
    }  
}

Solution

  • Before using them, try to check the doc's.
    Reason :

    Scanner.nextLine : The java.util.Scanner.nextLine() method advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

    While, this is not Applicable to Scanner.nextInt

    Hence, the Scanner.nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine.

    Basic Solution would be to use blank Scanner.nextLine after Scanner.nextInt just to consume rest of that line including newline.

    For Example

    int myVal1 = input.nextInt();
    input.nextLine(); 
    String myStr1 = input.nextLine();