Mohammad Hasan
Mohammad Hasan

Reputation: 71

Confusion with scanner class -> nextLine()

I have written a basic code to read different data types. But I can not enter the string as input. What am I missing ?

public class Main {

public static void main(String[] args) {
    Scanner read = new Scanner(System.in);
    int integer = read.nextInt();
    double Double = read.nextDouble();
    String string = read.nextLine();
    System.out.printf("String: %s\nDouble: %f\nInt: %d",string,Double,integer);
}
}

Upvotes: 1

Views: 189

Answers (1)

brso05
brso05

Reputation: 13232

You must "eat up" the newline character left over from the double.

Scanner read = new Scanner(System.in);
int integer = read.nextInt();
double Double = read.nextDouble();
read.nextLine();
String string = read.nextLine();
System.out.printf("String: %s\nDouble: %f\nInt: %d",string,Double,integer);

The problem is that after nextDouble() there is still a newline character out there so the scanner reads the next line which has nothing in it...

Upvotes: 4

Related Questions