greysqrl
greysqrl

Reputation: 977

Java Scanner - Input space separated doubles when the total number of items is unknown

I have a simple Java program that I'm running in Eclipse. From the command line I'm passing in a list of around 100 space separated doubles however, please assume that I don't know how many items could be passed in.

At the moment I'm reading in the entire line, then tokenizing and converting to doubles as shown below:

    Scanner sc = new Scanner(System.in);

    ArrayList<Double> stock = new ArrayList<Double>();

    String s = sc.nextLine();

    String[] split = s.split("\\s+");

    for (int i=0; i<split.length; i++)
    {
        stock.add(Double.parseDouble(split[i]));
    }

So, I'm relatively confident that the above is not the best way to approach such a problem. I want to do something more like the code below, however when I enter the data in the console and hit enter, the program fails to respond, as in, it's not recognising my input as a list of doubles.

    Scanner sc = new Scanner(System.in);

    ArrayList<Double> stock = new ArrayList<Double>();

    while (sc.hasNextDouble())
    {
        double d = sc.nextDouble();

        stock.add(d);
    }

So, at present the first code sample works fine, the second fails to do anything. Incidentally, I HAVE tried adding sc.nextLine(); after the sc.nextDouble(); call but that doesn't make a difference.

Is there something I'm doing wrong here or is there a better approach that I should be taking.

Thank you in advance.

Upvotes: 1

Views: 931

Answers (1)

Morten Kolstad
Morten Kolstad

Reputation: 26

It is because of the while-loop. The program will just wait for more input from System.in forever, because sc.hasNextDouble() will evaluate to true every time because input from System.in is infinite, unlike input from a file.

To me the first solution you have seems to be the way to go if you want to all the doubles in one line. But you can clean it up a little and use a for-each instead of a regular for-loop.

Example:

Scanner scanner = new Scanner(System.in);

ArrayList<Double> doubles = new ArrayList<Double>();

String inputLine = scanner.nextLine();
String[] splittedInputLine = inputLine.split("\\s+");

for(String doubleString : splittedInputLine) {
    doubles.add(Double.parseDouble(doubleString));
}

Upvotes: 1

Related Questions