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!
It’s because your first
br.readLine()would get your first line from the file, which is number of clubs. After theifstatement, which fails, you are callingbr.readLine(). This call would get the next line, as the first line was already retrived in the last call tobr.realLine()in theifstatement.Try this: