我正在编写一个程序,该程序从一个名为“grades.txt”的文件中读取,并显示学生的姓名,三个等级以及这三个等级的平均值。 文本文件如下所示:
Bobby
Doe
65
65
65
Billy
Doe
100
100
95
James
Doe
85
80
90
以下是代码: (代码有效。我能够从文件中读取并正确输出所有内容。)
import java.util.Scanner; // Needed for Scanner class.
import java.io.*; // Needed for I/O class.
public class TestScoresRead
{
public static void main(String[] args) throws IOException
{
// Open the file
File file = new File("Grades.txt");
Scanner inputFile = new Scanner(file);
// Read lines from the file
while (inputFile.hasNext())
{
String firstName = inputFile.next();
String lastName = inputFile.next();
double grade1 = inputFile.nextDouble();
double grade2 = inputFile.nextDouble();
double grade3 = inputFile.nextDouble();
String nextLine = inputFile.nextLine();
int total = (int)grade1 + (int)grade2 + (int)grade3;
int average = total / 3;
System.out.println("Name: \t" + firstName + " " + lastName);
System.out.println("Test 1:\t" + grade1);
System.out.println("Test 2: \t" + grade2);
System.out.println("Test 3: \t" + grade3);
System.out.println("");
System.out.println("Average: " + average);
if (average < 60)
System.out.println("Grade : \t F");
else if (average < 70)
System.out.println("Grade : \t D");
else if (average < 80)
System.out.println("Grade: \t C");
else if (average <90)
System.out.println("Grade: \t B");
else
System.out.println("Grade: \t A");
System.out.println("");
}
inputFile.close();
}
}
但是,我一直收到此错误,我不确定原因:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at TestScoresRead.main(TestScoresRead.java:21)
从我已经完成的研究中,我认为它与从nextLine到nextDouble有关,并且/ n被卡在键盘缓冲区中。 或者也许我没有使用hasNext吧? 有没有人有任何关于如何修复错误的建议? 先谢谢!
答案 0 :(得分:0)
删除此行
String nextLine = inputFile.nextLine();