just wondering what i am doing wrong here. i am trying to read from a file and parse through some data. i keep getting error "java.lang.NumberFormatException" that it can't parse the numbers. I know i use getNextDouble() or get nextInt() but im trying to keep the code as general as i can. Any thoughts would be greatly appreciated. ty.
here is a sample of a line from my text file:
foo Bar 19.35 55 987.0054 4
public void readFile(){
int i=0;
String line;
try{
fileIn = new Scanner(new File("pa1Names.txt"));
}catch(Exception e){
System.out.println("Fatal Error: File was not opened");
}
while(i<names.length && fileIn.hasNext()){
line = fileIn.nextLine();
StringTokenizer st = new StringTokenizer(line);
int m = st.countTokens();
names[i] = st.nextToken();
for (int k = 0; k<m-5; k++)
{
names[i] = names[i] + " " + st.nextToken();
}
reals[i][0] = Double.parseDouble(st.nextToken());
ints[i][0] = Integer.parseInt(st.nextToken());
reals[i][1] = Double.parseDouble(st.nextToken());
ints[i][1] = Integer.parseInt(st.nextToken());
i++;
}//end while
fileIn.close();
}
In your try/catch block, you need to put in a return statement in the catch block, or you need to move the rest of the code to be inside the try block (if the file open fails, even though you caught the error, the fileIn.HasNext will definitely fail because the file is still not open).
I also copied and pasted your code and ran it through a debugger, I think your first for loop is off, as names[i] is the following:
"foo" //names[i] = st.nextToken();
"foo bar" // first iteration of names[i] = names[i] + " " + st.nextToken();
"foo Bar 19.35" // second iteration of names[i] = names[i] + " " + st.nextToken();
The reals[i][0] then reads in the integer (55), so has a value of 55.0 The ints[i][0] is then throwing an exception because the next number is a double not an int.
So your for loop should be:
If I understood well, in your example
you read st.nextToken three times instead of two. Probably you need to use something like this:
You might want to use String.split() to first separate tokens into an array and then parse them one by one.
If you have controls on data format, it's better to use standard CSV.
Removing
names[i] = st.nextToken();
from your code should work fine.The problem was you were reading the first Token even before you went inside the
for
loop