chaitanya
chaitanya

Reputation: 11

what is the problem with string printing with the help of the code

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d= scan.nextDouble();
        String s = scan.nextLine(); 
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

Why I cannot print the string in the above code?

String: 
Double: 3.1415
Int: 42

Upvotes: 0

Views: 56

Answers (1)

mahfuj asif
mahfuj asif

Reputation: 1979

In the console when you are entering 42 and press enter, it takes 42 as int value and "enter"(or newline i.e /n) as string. But as there is no nextLine() after nextInt(), it avoids the newline. When you enter 3.1415 and press enter, it takes 3.1415 as double and enter/newline as string. So solution can be add another extra nextLine() after nextDouble()

Upvotes: 2

Related Questions