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;
}
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 thatin.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:
Hope this would be helpful,
Good Luck.