Darpanjbora
Darpanjbora

Reputation: 173

Scanner class fails to take string input

It is a simple java code.. but Scanner class isn't taking the string as input. why?

public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int x=sc.nextInt();
        double y=sc.nextDouble();
        String s =sc.nextLine();

        System.out.println("String: "+s);
        System.out.println("Double: "+y);
        System.out.println("Int: "+x);
}

Upvotes: 2

Views: 379

Answers (2)

karim mohsen
karim mohsen

Reputation: 2254

Because the sc.nextInt() and sc.nextDouble() method does not consume the newline character of your input, so that newline is consumed in the next call to sc.nextLine()

public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int x=sc.nextInt();
        sc.nextLine(); 
        double y=sc.nextDouble();
        sc.nextLine();
        String s =sc.nextLine();

        System.out.println("String: "+s);
        System.out.println("Double: "+y);
        System.out.println("Int: "+x);
}

Upvotes: 2

Baderous
Baderous

Reputation: 1069

Use nextLine() method to read all values and then parse them into the corresponding type (Integer, Double, etc). See why here: Integer.parseInt(scanner.nextLine()) vs scanner.nextInt()

Upvotes: 1

Related Questions