0
我想读取文本文件并在我的Java程序中打印响应。扫描仪跳过文本文件中的行并不打印前导空格
我的文本文件包含许多行,每行都包含一串等级。其中一些具有领先的空白(表示空白)。
我有两个问题: 1.文本文件中的第一行不打印;它从第二行开始 2.其中一条等级线在开始处包含两个“空格”,表示空格;这些空白处不打印。
以下是我的代码。任何输入到我如何解决这个问题?这里的新程序员非常感谢你的帮助。
public static void printResponses (File f) throws FileNotFoundException
{
Scanner input = new Scanner (f);
String line;
int count = 1;
while (input.nextLine() != null)
{
line = input.nextLine();
System.out.println ("Student #" + count +"\'s responses: " + line);
count++;
}
System.out.println ("We have reached \"end of file!\"\n");
if (!f.exists())
{
System.out.println ("An error occurred. Please try again.");
System.exit(0);
}
}
请注意,您如何在'while'循环中读取两行。 –
'Scanner'类具有'hasNextLine()'方法。 –
另外,'nextLine'永远不会返回'null'。 –