每條線由三部分信息組成,由whitespace分隔:name(String類型),ID(String類型)和gpa(double類型)。建築類學生
我試圖寫一個程序,讀取整數N和一個文件名,然後從輸入文件中讀取N行數據,將數據存儲在學生ArrayList中。你可以假設在這個問題中給出了Student類。我在代碼中遇到了一些問題,並且遇到了13個錯誤。如果任何人都可以提供幫助,那會很棒
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Students {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<Student>(); //this will be a list of all the students in the file
//we will add to this list as we read in students from the file
//using an ArrayList allows us to easily add students when we don't know how many there will be
Scanner stu = new Scanner(System.in);
Student s = null;
/*Part two: get the file name and intialize the file reader*/
try{
System.out.print("Enter filename: "); //prompt the user for the file name
filename = in.readLine(); //get the filename- user types this on the keyboard
fin = new BufferedReader(new FileReader(filename)); //create the file reader
//if the filename is invalid, an error message will be printed and the program terminated
}catch(Exception e){
e.printStackTrace();
}
/*Part three: read all of the student data from the file*/
s = getStudent(fin); //call the getStudent function to get the next student from the file
while(s != null){ //keep going until all students have been read
students.add(s); //add the new student to our ArrayList of students
s = getStudent(fin); //get the next student
}
/*Part four: print out the results*/
for(Student a: students){ //loop through all the students in our list
System.out.println(a.getFirstName()); //print out name
System.out.println(a.getId()); //print out ID number
System.out.println("Gpa: " + a.getGrade()); //print out gpa
}
}
}
Test case
Enter an integer: 3
Enter a filename: students.txt
[Wally 1234567 4.5, John 7654321 3.0, Susan 1212121 4.5]
需要 「在」 聲明變量, 「鰭」 – ravthiru
爲什麼我有 「在」 申報?不是Scanner的一部分 –
[Scanner](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)類沒有readLine()方法,也許你'想要[BufferedReader](https://docs.oracle.com/javase/7/docs/api/java/io/BufferedRead er.html#readLine())'in'。在使用它之前,必須向JVM聲明什麼是「in」。 – davedwards