EDIT: Simple fix installed with a check for a blank line. Chalk this up to me not fully understanding I/O yet and how the read.line() works.
Final code:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class MagicSquareAnalysis {
public static boolean testMagic(String pathName) throws IOException {
// Open the file
BufferedReader reader = new BufferedReader(new FileReader(pathName));
boolean isMagic = true;
int lastSum = -1;
// For each line in the file ...
String line;
while ((line = reader.readLine()) != null) {
// ... sum each row of numbers
String[] parts = line.split("\t");
int sum = 0;
for (String part : parts) {
if (line.isEmpty()) {
continue;
} else {
sum += Integer.parseInt(part);
}
}
if (lastSum == -1) {
// If this is the first row, remember the sum
lastSum = sum;
} else if (lastSum != sum) {
// if the sums don't match, it isn't magic, so stop reading
isMagic = false;
break;
}
}
reader.close();
return isMagic;
}
public static void main(String[] args) throws IOException {
String[] fileNames = { "C:\\Users\\Owner\\workspace\\MagicSquares\\src\\Mercury.txt", "C:\\Users\\Owner\\workspace\\MagicSquares\\src\\Luna.txt" };
for (String fileName : fileNames) {
System.out.println(fileName + " is magic? " + testMagic(fileName));
}
}
}
Original problem
Have a Java program that reads a .txt file of numbers. The text file has several rows of numbers spaced out by a tab. I continued to receive an error with line 22 of my program, which was this code:
sum += Integer.parseInt(part);
After a few statements to check the progress of the program, I discovered the error was occurring after the program analyzed the first line. For some reason the input it kept trying to read was a "" in the blank line. The read.line() did not seem to be skipping the blank line as it should have with the while statement.
Any ideas why the program is not skipping over the blank line and trying to read it regardless?