NoSuchElementException when reading input from command line

304 Views Asked by At

I am trying to read input from the command line and put it in an ArrayList. I do it multiple times in the program but one time is throws the NoSuchElementException. What am I doing wrong?

public static ArrayList<Double> getInfoTwo ()
{
    ArrayList<Double> infoListTwo = new ArrayList<Double>();
    Scanner in = new Scanner(System.in);
    System.out.println("Please enter your total hours: ");
    infoListTwo.add(in.nextDouble());
    in.close();
    return infoListTwo;
}
2

There are 2 best solutions below

0
On

Here is the problem:

When you run your getInfoTwo() method only one time in running your whole program, there is no problem. But when you call this method multiple times, for example in a loop, the exception occurs.

That is maybe because of closing the Scanners input stream. The second time when your program reaches to infoListTwo.add(in.nextDouble()); the inputStream is closed. Note that in.close(); will close the underneath inputStream, and that inputStream you passed to Scanner is System.in. System.in is a static variable. So maybe when you close it in one running session of your program, the next time it is already closed.

By the way, the important thing is to solve this problem. If you need to read more than one input from console and store it in a List, best possible solution is to move the business of read n input from console to your getInfoTwo() method, something like this:

public static ArrayList<Double> getInfoTwo(int n) {
    ArrayList<Double> infoListTwo = new ArrayList<Double>();
    Scanner in = new Scanner(System.in);
    for (int i = 0; i < n; i++) {
        System.out.println("Please enter your total hours: ");
        infoListTwo.add(in.nextDouble());
    }
    in.close();
    return infoListTwo;
}

Hope this would be helpful,

Good Luck.

0
On

it looks like your in.NextDouble() is throwing this. As per the Javadoc ( http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextDouble() )

This is because there is no data for the scanner to read. Try surrounding that call with in.hasNextDouble()

public static ArrayList<Double> getInfoTwo ()
{
    ArrayList<Double> infoListTwo = new ArrayList<Double>();
    Scanner in = new Scanner(System.in);
    System.out.println("Please enter your total hours: ");
    if (in.hasNextDouble()) {
       infoListTwo.add(in.nextDouble());
 
    }
    in.close();
    return infoListTwo;
}