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--;
   }
}
}
4

2 回答 2

2

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

于 2013-10-14T03:34:32.270 回答
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--;
        }
    }
}
于 2013-10-14T03:45:25.670 回答