I tried try and catch for double but it didn’t work [closed]

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);
    }

Leave a Comment