Search code examples
javajava.util.scanner

Error in reading double and string value from standard input?


Here is my code:

public class Solution {
    public static void main(String[] args) {
        /*
         * Enter your code here. Read input from STDIN.
         * Print output to STDOUT.
         * Your class should be named Solution.
         */
        int num = 0;
        double dou = 0.0;
        String s = null;
        Scanner in = new Scanner(System.in);
        if (in.hasNextInt()) {
            num = in.nextInt();
        }

        Scanner d = new Scanner(System.in);
        if (d.hasNextDouble()) {
            dou = d.nextDouble();
        }

        Scanner str = new Scanner(System.in);
        if (str.hasNextLine()) {
            s = str.nextLine();
        }

        System.out.println("String:" + s);
        System.out.println("Double:" + dou);
        System.out.println("Int:" + num);
    }
}

I am getting this output:

String:null
Double:0.0
Int:42

But it should should look like this:

String: Welcome to Hackerrank Java tutorials!
Double: 3.1415
Int: 42

Can anyone explain me why I'm getting a null value for the string and 0.0 for the double?


Solution

  • You should not use 3 scanners, one is enough. see Scanner method opened and closed twice.

    Apart from that, when using only one, there can still be a problem like in this question: Java String Scanner input does not wait for info, moves directly to next statement. How to wait for info?