|
-
May 4th, 2009, 06:03 AM
#1
BufferedReader problem
I am reading in a text file that has 9 items on 9 lines, however after reading the contents of the file and printing out what has been read by the BufferedReader, only lines 1,3,5 & 7 are being printed. The file format is as follows;
Code:
0 0 0 7 0 0 2 0 6
0 0 3 2 0 0 5 0 0
7 0 0 0 8 0 0 0 9
6 5 0 0 0 1 0 0 0
0 0 2 0 0 0 0 0 0
0 0 0 5 0 6 0 4 3
9 0 0 0 6 0 0 0 7
0 0 4 0 0 7 9 0 0
0 0 0 0 0 9 0 0 0
The java code is as follows;
Code:
if (button == load){
try{
JFileChooser fc = new JFileChooser();//new dialog
File selectedFile;
BufferedReader in;
FileReader reader = null;
fc.setCurrentDirectory(new File("." + "\\Puzzles"));
//opens dialog if button clicked
if (fc.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){
//gets file from dialog
selectedFile = fc.getSelectedFile();
//makes sure files can be processed before proceeding
if (selectedFile.canRead() && selectedFile.exists()){
reader = new FileReader(selectedFile);
}
}
in = new BufferedReader(reader);
String inputLine = null;
int lineCounter = 0;
while((inputLine = in.readLine())!= null && lineCounter < 10){
lineCounter ++;
System.out.println("Line " + lineCounter + ":" + inputLine);
inputLine = in.readLine();
dialog.setText("Status: Puzzle Loaded!");
}
in.close();
System.out.println("File Closed");
}
//catches input/output exceptions and all subclasses exceptions
catch(IOException ex){
System.out.println("Error Processing File:\n" + ex.getMessage()+"\n");
}
//catches nullpointer exception, file not found
catch(NullPointerException ex){
System.out.println("Open File Cancelled:\n" + ex.getMessage()+"\n");
}
}
Any help would be appreciated
-
May 4th, 2009, 06:26 AM
#2
Re: BufferedReader problem
Solved!
removed the second inputLine = in.readLine() from the while loop.
No need to read the line twice!
j
-
May 4th, 2009, 09:26 AM
#3
Re: BufferedReader problem
Yes, it's an easy mistake to make - especially if you combine too many side-effects into a single expression. That loop condition follows the old-school C idiom that both reads from the input and checks for an end-condition in a single expression - a clever optimization that may once have saved a few bytes of memory or some CPU time, but now just makes the code a little harder to follow. I'd be inclined to use separate expressions to read from the input and check for the end-condition.
Programs must be written for people to read, and only incidentally for machines to execute...
H. Abelson and G. Sussman
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|