sentientmachine
sentientmachine

Reputation: 357

Reading multiple numbers on a single line with Scanner

I need to read multiple numbers (don't know how many numbers I'm going to read, but I know they are at most six numbers) from a single line using a Scanner. I tried something found on the net but I couldn't find a solution. The reading stops when the user writes -1. Here's what I wrote up to now:

Scanner read = new Scanner(System.in);
int i;
float buffer[] = new float[6];

while (read.nextInt() != -1) {
            if (read.hasNextInt()) {
                buffer[i] = read.nextInt();
                i++;
            } else {
                break;
            }
        }

When I try to run this, I get a NoSuchElementException, but I don't understand why. What's wrong with this code? How can I correct this? Thanks in advance.

Upvotes: 2

Views: 1037

Answers (2)

Or you can read line once, and split it in integers

   line=scanner.nextLine();

   // split there
   String elements[]=line.split("\\W+");

   // convert to int    
   for (int i=0;i<elements.length;i++)
       ints[counter++]=Integer.parseInt(elements[i]);

   // check
   for (int i=0;i<counter;i++)
       System.out.println("INT ["+i+"]:"+ints[i]);

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201429

Because you aren't checking if the Scanner has another int (and a Scanner doesn't return -1 when it does not have another element). This

while (read.nextInt() != -1) {

needs to be something like

while (read.hasNextInt()) {
    int val = read.nextInt();
    if (val == -1) {
        break;
    }
    buffer[i] = val;
    i++;
}

Upvotes: 2

Related Questions