使用BufferedReader读取行

时间:2015-08-01 11:54:42

标签: java

我正在尝试从文件中读取信息来解释它。我想读取每一行输入。我刚刚了解了bufferedreader。但是,我的代码的问题是它会跳过其他所有行。

例如,当我输入8行数据时,它只打印4行。偶数的。

以下是代码:

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:");
   }
 }
 }

我知道这可能是一种糟糕的写作风格。我只是新编码。所以,如果有任何方法可以帮助我修复代码和方法的风格,我会非常激动。

该计划的目的是将答案与正确答案进行比较。 因此,我还有 另一个问题

如何将字符串与缓冲读卡器进行比较? 比如我如何比较ABCCED和ABBBDE,看看前两个匹配,但其余的不匹配。

谢谢

2 个答案:

答案 0 :(得分:1)

  

我的代码的问题是它会跳过其他所有行

您的EOF检查会在每次迭代时留下一行

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
}

阅读所有行,请执行以下操作:

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
}

要比较字符串,您需要使用String#compareTo(String other)方法。如果返回值为0,则两个字符串相等。

答案 1 :(得分:0)

您不能将字符串与readLine()进行比较。您将它们与String.equals().

进行比较

由于duplicate中提到的原因,您的阅读代码会跳过每一条奇数行。