2017-10-19 53 views
0

我正在写一个程序,从名为“grades.txt”的文件读取并显示学生的姓名,三等级,以及这三个等级的平均值。 文本文件看起来像这样:Java - 从文件读取 - 错误“线程中的异常”主“java.util.NoSuchElementException:没有找到行”

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) 

从我所做的研究,我相信我t与从nextLine到nextDouble有关,而/ n被卡在键盘缓冲区中。 或者,也许我不使用hasNext权利? 有没有人有任何建议如何解决错误? 感谢先进!

回答

0

删除此行

String nextLine = inputFile.nextLine(); 
+0

我不知道我错过了,但那是修复。谢谢!! –

相关问题