-
Help with Code
Alright so the object of the program is to input data from a text file. However, I'm having issues when parsing the text file. BlueJ returns a java.lang.NumberFormatException: for Input String: "945" at the pressure[number] line. Are there any other ways to work this program?
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.io.PrintWriter;
public class Hurricanes2
{
public static void main(String[] args) throws IOException
{
File hurricaneData = new File("hurcdata.txt");
Scanner inFile = new Scanner(hurricaneData);
PrintWriter outFile = new PrintWriter (new File("Summary.txt"));
int index = 0;
while(inFile.hasNextLine())
{
String blank = inFile.nextLine();
index++;
}
int[ ] years = new int[ index ];
String[ ] month = new String [ index ];
int[ ] pressure = new int [ index ];
int [ ] windSpeed = new int [ index ];
String[ ] name = new String [ index ];
int number = 0;
File hurricaneData2 = new File("hurcdata.txt");
Scanner inFile2 = new Scanner(hurricaneData2);
while(inFile2.hasNextLine())
{
String data = inFile2.nextLine();
String year = data.substring(0 , 4);
years[number] = Integer.parseInt(year);
String monthOfHurricane = data.substring(5 , 8);
month[number] = monthOfHurricane;
int y = data.indexOf("", 9);
int x = data.indexOf("", 13);
String pressureOfHurricane = data.substring(y, x );
pressure[number] = Integer.parseInt(pressureOfHurricane);
int z = data.indexOf("", 15);
String windSpeedofHurricane = data.substring(x, (z+1));
windSpeed[number] = Integer.parseInt(windSpeedofHurricane);
String nameOfHurricane = data.substring((z+1));
name[number] = nameOfHurricane;
number++;
}
System.out.println(years[3]);
System.out.println(month[3]);
System.out.println(pressure[3]);
System.out.println(windSpeed[3]);
System.out.println(name[3]);
inFile.close();
}
}
First lines of text file:
1980 Aug 945 100 Allen
1983 Aug 962 100 Alicia
1984 Sep 949 100 Diana
1985 Jul 1002 65 Bob
-
Re: Help with Code
Please use [code] tags [/code] when posting code.
Check how your splitting of the line is working by printing out each element as you substring it, complete with '-' before and after.
eg
Code:
System.out.println("-" + y + "-");
I expect there's a space character in there causing the exception.
-
Re: Help with Code
That seems to be the issue. There's space characters in the string. However, why is this occurring?
Because I used indexOf to find the spaces shouldn't the program have found the first space and skipped over it? How can I remedy my situation?
-
Re: Help with Code
All I can say is that the index is wrong somewhere.
Can I suggest simply using the split() method?
That's the usual way of doing this.
-
Re: Help with Code
Please go through the Forum Rules -- particularly the third paragraph.
db