2

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);
}
Darpanjbora
  • 163
  • 3
  • 13

2 Answers2

2

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);
}
karim mohsen
  • 2,164
  • 1
  • 15
  • 19
1

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()

Community
  • 1
  • 1
Baderous
  • 1,069
  • 1
  • 11
  • 32