My code is as such:
public static void main(String args[]) throws IOException
{
String name;
int population;
String[] tokens;
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
src.useDelimiter(",");
while (src.hasNextLine())
{
if (src.hasNext())
{
tokens = src.nextLine().split(",\\s");
name = tokens[0];
population = Integer.parseInt(tokens[1].trim());
System.out.printf("Name:%-15s %-15d\n", name, population);
} else
{
String str = src.next();
if (str.equals(""))
{
break;
} else
{
System.out.println("File format error.");
return;
}
}
}
System.out.println("end");
fin.close();
}
In my test file, I just have a state’s name followed by a comma, a space, the population, and possibly a random space after the population. My output results as
…..
Name:Virginia 7100702
Name:Washington 5908684
Name:West Virginia 1813077
Name:Wisconsin 5371210
Name:Wyoming 495304
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 1
at javatesters.JavaTesters.main(JavaTesters.java:35)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
The end of my test file is
Virginia 7100702
Washington 5908684
West Virginia 1813077
Wisconsin 5371210
Wyoming 495304Total Apportionment Population 281424177 435
And I want the blank line to indicate the end of the file
When your scanner gets down to a line that doesn’t include a “, “, that
split(",\\s")call splits it into just one string. So, when you accesstokens[1], you’re going out of bounds of the array. There are lots of ways to work around this. One approach (though not the cleanest) would be to check to make suretokenshas two elements before you use it.