import java.io.*;
import java.util.*;
public class Statistics {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("C:\\Users\\user\\Desktop\\students.dat"));//Opened file
int math=0,spanish=0,french=0,english=0,count=0,sum,highSpan=0,highMath=0,highFren=0,highEng=0;//Declarations
double avg,highAvg=0;
String name,highName;
highName="";
name = ""; //Prime read
while (name!="ENDDATA"){ //Sentinel condition
count++; //Keeps count of students
name = in.next();
spanish=in.nextInt();
math=in.nextInt();
french=in.nextInt();
english=in.nextInt();
sum = spanish + math + french + english;
avg = sum/4; //Claculates Average
System.out.printf("%s - %.0f\n",name,avg);
if (avg > highAvg){ //Checks for the highest Average
highAvg = avg;
highName = name;
}
if (spanish > highSpan){
highSpan = spanish;
}
if (math > highMath){
highMath = math; //Checks for the highest mark for each subject
}
if (french > highFren){
highFren = french;
}
if (english > highEng){
highEng = english;
}
name = in.nextLine();
}
System.out.printf("Number of students in class is: %d\n",count);
System.out.printf("The highest student average is: %f\n",highAvg);
System.out.printf("The student who made the highest average is: %s\n",highName);
System.out.printf("The highest Spanish mark is: %d\n",highSpan);
System.out.printf("The highest Math mark is: %d\n",highMath);
System.out.printf("The highest French mark is: %d\n",highFren);
System.out.printf("The highest English mark is: %d\n",highEng);
in.close(); //Closing of file
}
}
寫Java程序讀取和處理文本文件的每一行,並打印以下 信息(每個最後一行除外): 該班級中的學生人數 每名學生的姓名和平均分數 班級中的最高學生平均分(忽略平局的可能性) 獲得最高平均分的學生的名字(忽略配合的可能性) 每個科目的最高分數每次我編譯while循環超出了我的項目一切不露面(輸入來自文件)
其應該讀取的數據形式的數據文件,並作出必要的輸出,但在while循環外的打印語句不顯示,我也得到這個輸出與下面的錯誤。
MARY - 65
SHELLY - 70
JOHN - 60
ALFRED - 71
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Statistics.main(Statistics.java:17)
它必須是因爲'while'循環還沒有完成。檢查你的數據。由於MARY,SHELLY等成功打印,因此特定學生的數據必須有錯誤。 – jmcg 2015-04-01 03:30:37
你的錯誤顯示'nextInt'正在拋出錯誤並終止程序。你應該檢查你的文件,並確保你試圖讀取的項目確實是一個整數。如果你用最小的** students.dat **的內容更新你的問題是最好的,這會導致這個錯誤發生。 – 2015-04-01 03:33:01