我正在编写一个程序,打印出字母等级,平均值基于它从我设置的文本文件中读取的内容。文本文件中已经包含一些样本编号(整数)。
它编译,但是当我运行它时会突出显示“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 :(得分:2)
您需要检查是否有另一个整数可以使用in.hasNextInt()
作为while循环条件进行读取。
答案 1 :(得分: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--;
}
}
}