gpt4 book ai didi

java - 使用 BufferedReader 读取行

转载 作者:行者123 更新时间:2023-11-30 08:02:01 25 4
gpt4 key购买 nike

我正在尝试从文件中读取信息来解释它。我想读取每一行输入。我最近刚刚了解了 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 进行比较,以查看前两个匹配但其余的不匹配。

谢谢

最佳答案

the problem with my code is that it skips every other line

您的 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,则两个字符串相等。

关于java - 使用 BufferedReader 读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31761544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com