>我的任务是创建一个简单的java程序,该程序读取数据文件中的成绩,然后计算以下每个组中有多少个成绩
: [90 - 100] [80 - 89] [70 - 79] [60 - 69] [低于60] 下面是示例输出: [90 - 100] 10 [80 - 89] 9 [70 - 79] 20 [60 - 69] 8 [60以下] 2.这是我到目前为止编码的内容:
//Import the needed header files
import java.util.*;
import java.io.*;
//Class
public class GradeDistribution
{
public static void main(String[] args) throws FileNotFoundException{
//Sets up varaibles and assign string numbers to int values
Scanner input=new Scanner(new File(args[0]));
//Declare the needed varaibles and initialize them
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int sCount = 0;
//Loop to read till the "data.txt" has scores
while(input.hasNextInt())
{
//Increment score counter
sCount++;
//Read scores
input.nextInt();
}
//Score array
int score[] = new int[sCount];
//Loop to iterate through the scores
for(int i=0;i<sCount;i++)
{
//Read
score[i]=input.nextInt();
//Check condition for [90-100]
if (score[i]<=100 && score[i]>=90)
{
//Increment count1
count1 = count1 + 1;
}
//Check condition for [80-89]
else if (score[i]<90 && score[i]>=80)
{
//Increment count2
count2 = count2 + 1;
}
//Check condition for [70-79]
else if (score[i]<80 && score[i]>=70)
{
//Increment count3
count3 = count3 + 1;
}
//Check condition for [60-69]
else if (score[i]<70 && score[i]>=60)
{
//Increment count4
count4 = count4 + 1;
}
//Otherwise below 60
else
{
//Increment count5
count5 = count5 + 1;
}
}
//Print
System.out.println("[90-100] "+count1);
System.out.println("[80-89] "+count2);
System.out.println("[70-79] "+count3);
System.out.println("[60-69] "+count4);
System.out.println("[below 60] "+count5);
}
}
代码看起来和逻辑上是可执行的,但是当我运行它时,我收到此错误,
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at GradeDistribution.main(GradeDistribution.java:43)
为什么?
java.util.InputMismatchException
是指您使用Scanner
接受某种类型(例如int
、String
或char
(,但输入了不同的类型。例如,如果您调用 nextInt()
并输入 String
,则会引发此异常。
代码中的问题可能出在第一个while
循环中,即调用 input.nextInt()
。这只检查整数,而你的文件可能包含一个字符串。
因为你迭代不正确。什么;此代码的目的是什么?然后再次迭代?
//Loop to read till the "data.txt" has scores
while(input.hasNextInt())
{
//Increment score counter
sCount++;
//Read scores
input.nextInt();
}