2013-10-14 44 views
1

我正在编写一个程序,它将打印出字母等级,并根据它从我设置的文本文件中读取的平均值进行平均。文本文件已经有一些样本数字(整数)。没有这样的元素异常错误?

它编译,但是当我运行它时,它突出显示“int grade = in.nextInt();”并给我以下错误:

java.util.NoSuchElementException 
at java.util.Scanner.throwFor(Scanner.java:907) 
at java.util.Scanner.next(Scanner.java:1530) 
at java.util.Scanner.nextInt(Scanner.java:2160) 
at java.util.Scanner.nextInt(Scanner.java:2119) 
at Prog2.main(Prog2.java:26) 

任何帮助表示赞赏!

public class Prog2 
{ 
public static void main(String args[]) throws Exception 
{ 
    Scanner in = new Scanner(new File("prog2test.txt")); 
    int scores = (in.nextInt()); 
    int A = 0; 
    int B = 0; 
    int C = 0; 
    int D = 0; 
    int F = 0; 

    while (scores > 0) 
    { 
     int grade = in.nextInt(); 
     if (grade >= 90) 
     { 
     A++; 
     } 
     else if (grade >= 80) 
     { 
     B++; 
     } 
     else if (grade >= 70) 
     { 
     C++; 
     } 
     else if (grade >= 60) 
     { 
     D++; 
     } 
     else 
     { 
     F++; 
     } 

     scores = scores--; 
    } 
    scores = 0; 
    while (scores > 0) 
    { 
     System.out.println(in.nextInt()); 
     scores--; 
    } 
} 
} 
+0

我认为,它无法找到prog2test.txt – gjman2

+0

IF((sourceClosed)&&(位置== buf.limit())) 抛出新NoSuchElementException异常(); – Sstx

+0

因此,猜测1.正如gjman所说,2.无法找到令牌,位置在文件末尾 – Sstx

回答

2

您需要检查是否有另一个整数以in.hasNextInt()作为while循环条件读取。

+0

作为while循环条件,您的意思是什么?而不是当前的“分数> 0”? – coinbird

+0

我猜测得分是要分析的分数。while循环应该是while(score> 0 && in.hasNextInt()),它确保它只会尝试扫描,如果有另一个整数(所以nextInt不会抛出NoSuchElementException,这是当它试图扫描不存在的东西时) – user2816823

+0

啊!使用AND!非常感谢! – coinbird

1

尝试这样...当你打印出变量...你正在放入in.nextInt()没有任何检查...做一些RnD那里...但是,这段代码打印一些任意结果。

import java.io.File; 
import java.util.Scanner; 



public class Prog2 
{ 
    public static void main(String args[]) throws Exception 
    { 
     Scanner in = new Scanner(new File("prog2test.txt")); 
     int scores = (in.nextInt()); 
     int A = 0; 
     int B = 0; 
     int C = 0; 
     int D = 0; 
     int F = 0; 

     while (scores > 0&& in.hasNextInt()) 
     { 
      int grade = in.nextInt(); 
      if (grade >= 90) 
      { 
       A++; 
      } 
      else if (grade >= 80) 
      { 
       B++; 
      } 
      else if (grade >= 70) 
      { 
       C++; 
      } 
      else if (grade >= 60) 
      { 
       D++; 
      } 
      else 
      { 
       F++; 
      } 

      scores = scores--; 
     } 

     //scores = 0; 
     while (scores > 0) 
     { 
      System.out.println(scores); 
      scores--; 
     } 
    } 
} 
相关问题