Question

I am writing a simple program to read from System.in and place the info into an array of LinkedLists. I am having a pretty simple problem but after hours I can't seem to find the problem. Hopefully its nice and obvious. The segment of code throwing the NoSuchElementException is this:

while(scanner.hasNextLine())
{
        int index = scanner.nextInt();
        master[index].addObservation(scanner.next());
}

The error is being thrown from the line with the call to the nextInt() method. The problem occurs when I press Cntrl+Z to end input. For some reason, my code is still entering the while loop even though there is not another line of input. The input is in the following form:

1 doug
2 edwin
5 casey
4 fred
Cntrl+Z

(The pc number followed by the username)

The pc number is being used for the array index and the username is going into the linked list. I have tried placing the EOF char at the end of the last line and as the first char of the last line with no changes. Any help is greatly appreciated. Thanks!

FULL CLASS

import java.util.*;

public class TermReport 
{

        private static LineUsageData[] master = new LineUsageData[501];
        private static Scanner scanner = new Scanner(System.in);

        public static void main(String[] args)
        {
            //skip index 0 for index to PC clarity
            for(int i=1; i<501; i++)
            {
                master[i] = new LineUsageData();
            }

            while(scanner.hasNextLine())
            {
                int index = scanner.nextInt();
                master[index].addObservation(scanner.next());
            }
        }
}
Was it helpful?

Solution

Try replacing the row...

while(scanner.hasNextLine())

...with something like this:

while(scanner.hasNextInt())

It's another method of the Scanner class.

  • boolean hasNextInt()
    Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method.

I'm guessing the input you are scanning ends with something other than an int value.

OTHER TIPS

The most likely problem is that you have probably forgotten to initalize the array. You need something along the lines of

master = new ObservationList[MAX_INDICIES];

in front of the while loop.

It this is not the case, you will need to provide more code so we can see what you are doing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top