I'm grappling with a specific problem, but seeing as this is technically homework and I want to learn what I'm doing wrong, I would love a more general solution. Some caveats: I have to use the scanner class, and my data is not in an array or anything. I know from reading around on the site that BufferedReading is preferred. From what I've read of it, I think I would prefer it too. But that's not what I'm allowed to work with here.
I'm trying to read from a data file and then do some stuff with that file. The data goes like this:
1234 55 64 75
1235 44 32 12
...
nnnn xx yy zz
0
2234 47 57 67
2235 67 67 67
...
nnnn xx yy zz
0
Each line is an ID followed by three grades. Each class is terminated by a zero line and then the while loop starts from the top:
while (classContinues == true) {
//get the student's data and assign it in the program
studentID = inputFile.nextInt();
programGrade = inputFile.nextInt();
midtermGrade = inputFile.nextInt();
finalGrade = inputFile.nextInt();
// in here I'm doing other stuff but I don't need help with that
// check if the class has more students
if (inputFile.nextInt() == 0) {
classContinues = false;
} else {
classContinues = true;
inputFile.nextLine(); // eat the rest of the line
}
}
Now, when you run the code like this, it manages to print the output I want, but it skips every other row of data. Remove the inputFile.nextLine(); and it skips the second student ID and then messes up all the other output. So I guess what I'd like to know is what I'm doing wrong--how should I be checking for the next integer to be zero without eating the next student ID?
Store every line into a String variable, parse integers from that line and then assign them by reading it from that string, not from the line itself. So:
String nextLine;
while (classContinues)
{
nextLine = inputFile.nextLine();
String[] tokens = nextLine.split(" ");
if(tokens.length == 1) //this means line has '0' character
classContinues = false;
else
{
classContinues = true;
studentID = tokens[0];
programGrade = tokens[1];
midtermGrade = tokens[2];
finalGrade = tokens[3];
// your stuff
}
}
If there will be any kind of error that will show misleading results with this code, it is probably my bad because I don't know the rest of the project. So I posted a code similar to yours.
Also you have to do a null check to that String that you got from nextLine method.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments