Reputation: 35
I have a text file that provides information for 22 golf courses, including name of course, name, location, designer, greens fee, par, year built, and total yards. As I read in, each line needs to be stored to the appropriate variable and then used to create a few objects. The first line of the file is the number of golf courses in the text file.
FileInputStream fstream = new FileInputStream(System.getProperty("user.dir")
+ "\\GolfCourses.txt");
//use file
DataInputStream in = new DataInputStream(fstream);
//read input
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Tree newTree = new Tree();
try{
String line = br.readLine();
if(line==null)
throw new IOException();
int clubs = Integer.parseInt(line);
for(int i = 0; i < clubs; i++){
String name = br.readLine();
String location = br.readLine();
double fee = Double.parseDouble(br.readLine());
int par = Integer.parseInt(br.readLine());
String designer = br.readLine();
int built = Integer.parseInt(br.readLine());
int yards = Integer.parseInt(br.readLine());
newTree.insert(new TreeNode(new GolfCourse(name, location, designer, fee, par, built, yards)));
}
in.close();
}catch(IOException e){
System.out.println(e);
}
The read-in seems to jump ahead of itself, so the program is trying to parse strings instead of numbers. I've never had this problem before so I'm lost on how to fix it.
EDIT: The code is now working as intended. The issue was coming from the "i <= clubs" piece of the for loop. Thank you for taking the time to help!
Upvotes: 2
Views: 2753
Reputation: 33534
Read the file like this:
File f = new File("Path");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
Retriving of Fields:
If the fields like golf courses, name, locations are on a single line separated by "single space" for each entry:
- Use split(" ");
If the fields like golf courses, name, locations one per each line:
- Use split("\n");
Not "\\" but "\"
- Use for-loop
with count of 8
, so to get 8 fields.
Creation of Object:
- Create a Java bean
with 8 fields, to hold these values.
Upvotes: 1
Reputation: 46408
It's because your first br.readLine()
would get your first line from the file, which is number of clubs. After the if
statement, which fails, you are calling br.readLine()
. This call would get the next line, as the first line was already retrived in the last call to br.realLine()
in the if
statement.
Try this:
String line = br.readLine();
if(line == null) {
throw new IOException();
}
int clubs = Integer.parseInt(line);
Upvotes: 1