0

I'm trying to make a scanner read through a file. However, the problem is that the scanner keeps skipping the 0 position in the array. Below is the code and the output.

public void loadLocations(String fname) throws Exception {

        Scanner in = new Scanner(new File(fname));
        Locations = new String[in.nextInt()]; 
        in.reset();
        //writes lines to array.
        for (int i = 0; i < Locations.length; i++){     
            if (in.hasNextLine()){
                Locations[i] = in.nextLine();
            }

            else if (in.hasNext()) {
                Locations[i] = in.nextLine();

            }

        }   

        // close file
        in.close();
    }

This is the output

Loaded 4 cities: 
    has location id 0
    New York has location id -1
    Los Angeles has location id 2
    Chicago has location id -1
mjkaufer
  • 4,047
  • 5
  • 27
  • 55

1 Answers1

1

I think in.nextInt() does not automatically go to the next line. So you are reading the rest of that first line as blank.

Try replacing in.reset() with in.nextLine()

Ted Bigham
  • 4,237
  • 1
  • 26
  • 31