0
因此,我們希望應用程序允許用戶輸入學生的姓名和成績,並提示用戶輸入要創建的文件的名稱以及要輸入的學生數量(每個學生1個等級)。然後該程序將獲取所有成績並對其進行平均。問題是它沒有讀取文件,總是給我們-0.0的平均值。Java文件問題
`
public static void main(String[] args) throws IOException {
System.out.println("What is the name of the file you would like to create?");
filename = p.next();
File fd = new File(filename + ".txt");
fd.createNewFile();
students(fd);
}
public static void students(File fd) throws IOException {
int numbstudents;
FileWriter ap = new FileWriter(fd, true);
BufferedWriter ad = new BufferedWriter(ap);
System.out.println("How many students would you like to add?");
numbstudents = p.nextInt();
int i = 0;
while (i != numbstudents) {
for (i = 0; i < numbstudents; i++) {
System.out.println("What is the name of student number " + i + " ?");
String name = p.next();
ad.write(name);
ad.newLine();
System.out.println("What grade did student number " + i + " acheive?");
String a = f.next();
ad.write(a);
ad.newLine();
}
}
read(fd);
ad.close();
}
public static void read(File fd) throws FileNotFoundException {
int counter = 0;
FileReader h;
BufferedReader g;
String test;
double average, total = 0;
int number = 0;
int i = 0;
try {
h = new FileReader(fd);
g = new BufferedReader(h);
while ((test = g.readLine()) != null) {
number += 1;
System.out.println(test);
counter = counter + 1;
i = counter % 2;
if (i == 0) {
total += Double.parseDouble(test);
}
}
average = total/(number - 1);
System.out.println("The students average is: " + average);
g.close();
fd.delete();
} catch (FileNotFoundException e) {
System.out.println("File could not be found.");
} catch (IOException e) {
System.out.println("Your file could not be read.");
}
}
} `
嘗試調用'ad.close();''之前'讀取(fd);' – nandsito
也許問題是文件的內容;不能說,因爲你沒有分享它。 –
我想嘗試使用這裏提到的掃描儀:[使用掃描儀讀取.txt文件](http://stackoverflow.com/questions/13185727/reading-a-txt-file-using-scanner-class-in- JAVA) –