-6
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int i=scan.nextInt();

    // double d=scan.nextDouble();
    // Write your code here.

    Double d = 0.0;

    try {

         d = Double.parseDouble(scan.nextLine());

    } catch (NumberFormatException e) {

        e.printStackTrace();

    }

    String s=scan.nextLine();

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
}
Douwe de Haan
  • 5,038
  • 1
  • 24
  • 37
Aditya
  • 3
  • 3

2 Answers2

0

Your code can be changed to the following (remember that it's always a good idea to close the scanner):

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    String s = scan.nextLine();
    int i = scan.nextInt();
    double d = scan.nextDouble();

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
    scan.close();
}
Christian
  • 56
  • 5
0

It's because when you enter a number and press Enter key, scan.nextInt() consumes only the entered number, not the "end of line". When scan.nextLine() executes, it consumes the "end of line" still in the buffer from the first input which you have provided during the execution of scan.nextInt() .

Instead, use scan.nextLine() immediately after scan.nextInt().

in your current scenario you will get the exception,

java.lang.NumberFormatException: empty String

Your modified code will be as,

public static void main(String args[])


    {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        scan.nextLine();
        // double d=scan.nextDouble();
        // Write your code here.

        Double d = 0.0;

        try {

            d = Double.parseDouble(scan.nextLine());

        } catch (NumberFormatException e) {

            e.printStackTrace();

    }

        String s = scan.nextLine();

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
Zia
  • 1,080
  • 10
  • 23