Reputation: 167
I am trying to read information from a file to interpret it. I want to read every line input. I just recently learned about bufferedreader. However, the problem with my code is that it skips every other line.
For example, when I put in 8 lines of data, it only prints 4 of them. The even ones.
Here is the code:
import java.io.*;
import java.util.Scanner;
public class ExamAnalysis
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
int numOfQ = 10;
System.out.println();
System.out.println("Welcome to Exam Analysis. Let’s begin ...");
System.out.println();
System.out.println();
System.out.println("Please type the correct answers to the exam questions,");
System.out.print("one right after the other: ");
Scanner scan = new Scanner(System.in);
String answers = scan.nextLine();
System.out.println("What is the name of the file containing each student's");
System.out.print("responses to the " + numOfQ + " questions? ");
String f = scan.nextLine();
System.out.println();
BufferedReader in = new BufferedReader(new FileReader(new File(f)));
int numOfStudent= 0;
while ( in.readLine() != null )
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " + in.readLine());
}
System.out.println("We have reached “end of file!”");
System.out.println();
System.out.println("Thank you for the data on " + numOfStudent+ " students. Here is the analysis:");
}
}
}
I know this may be a bit of a bad writing style. I am just really new to coding. So if there is any way you can help me fix the style of the code and methods, I would be really thrilled.
The point of the program is to compare answers with the correct answer. Thus I also have another question:
How can I compare strings with the Buffered Reader? Like how can I compare ABCCED with ABBBDE to see that the first two match but the rest don't.
Thank you
Upvotes: 1
Views: 101
Reputation: 17595
the problem with my code is that it skips every other line
Your EOF check thows a line away on each iteration
while ( in.readLine() != null ) // read (first) line and ignore it
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " +
in.readLine()); // read (second) next line and print it
}
to read all line do the following:
String line = null;
while ( null != (line = in.readLine())) // read line and save it, also check for EOF
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " +
line); // print it
}
To compare Strings you need to use the String#compareTo(String other) method. Two Strings are equal if the return value is 0
.
Upvotes: 1
Reputation: 310840
You don't compare Strings with readLine()
. You compare them with String.equals().
Your reading code skips every odd line for the reason mentioned in the duplicate.
Upvotes: 0