0

I have an assignment where I have to read in a file with information about hurricanes from 1980 to 2006. I can not figure out what the error is. I have a section of code like this:

import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class Hurricanes2
{
public static void main(String[] args)throws IOException
{
    //declare and initialize variables


    int arrayLength = 59;
    int [] year = new int[arrayLength];
    String [] month = new String[arrayLength];



    File fileName = new File("hurcdata2.txt");
    Scanner inFile = new Scanner(fileName);

    //INPUT  - read data in from the file
    int index = 0;
    while (inFile.hasNext()) {
        year[index] = inFile.nextInt();
        month[index] = inFile.next();
    }
    inFile.close();

That is just the first part. But in the section with the while statement, there is an error with the year[index] = inFile.nextInt(). I have no idea what the error means and I need help. Thanks in advance.

Andreas
  • 19,756
  • 7
  • 41
  • 49

2 Answers2

0

Try adding index++ as the last line of your while loop. As it is now, you never increment it, so you're only filling and replacing the first numbers in your array.

Ari
  • 1
  • 2
0

I personally wouldn't use Scanner() but instead Files.readAllLines(). It might be easier to implement if there is some sort of delimiting character to split the hurricaine data on.

For instance, let's say your text file is this:

1996, August, 1998, September, 1997, October, 2001, April...

You can do the following if these assumptions I've made hold true:

Path path = Paths.get("hurcdata2.txt");
String hurricaineData = Files.readAllLines(path);

int yearIndex = 0;
int monthIndex = 0;

// Splits the string on a delimiter defined as: zero or more whitespace, 
// a literal comma, zero or more whitespace
for(String value : hurricaineData.split("\\s*,\\s*"))
{
    String integerRegex = "^[1-9]\d*$";
    if(value.matches(integerRegex))
    {
        year[yearIndex++] = value;   
    }
    else
    {
        month[monthIndex++] = value;
    }
}
j.seashell
  • 717
  • 9
  • 19