Это мой вопрос.ReadFile and Split info
(f)Define a method, public String toString(), that returns a String consisting of the Student object’s admin number, name and average score.
(h)Define another constructor with the method signature Student(String studentRecord),where studentRecord is of the format given below: adminNo;name;day/month/year;test1;test2;test3 birthdate
Example of a given string: 031234F;Michael Tan;01/08/1980;60;70;98
(i)Break up studentRecord into its constituent elements and use them to initialise the class variables, adminNo, name, birthdate, test1, test2, test3.
(i) Define a main() method to read a single record from the "student.txt" and **display the admin number, name and average score of the student.**
И вот мой код:
public class Student {
String adminNo;
String name;
GregorianCalendar birthDate;
int test1,test2,test3;
public Student(String adminNo,String name,String birthDate,int test1, int test2, int test3){
this.adminNo = adminNo;
this.name = name;
this.birthDate = MyCalendar.convertDate(birthDate);
this.test1 = test1;
this.test2 = test2;
this.test3 = test3;
}
public Student(String studentRecord){
Scanner sc = new Scanner(studentRecord);
sc.useDelimiter(";");
adminNo = sc.next();
name = sc.next();
birthDate = MyCalendar.convertDate(birthDate.toString());
test1 = sc.nextInt();
test2 = sc.nextInt();
test3 = sc.nextInt();
}
public int getAverage(){
return ((test1 + test2 + test3)/3) ;
}
public String toString(){
return (adminNo + " " + name + " " + getAverage());
}
public static void main(String [] args){
Student s = new Student ("121212A", "Tan Ah Bee", "12/12/92", 67, 72, 79);
System.out.println(s);
String fileName = "student.txt";
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
}
И это формат информации ИНТ текстового файла:
031234F;Michael Tan;01/08/1980;60;70;98
мне удалось напечатать:
121212A Tan Ah Bee 72
031234F;Michael Tan;01/08/1980;60;70;98
123456J;Abby;12/12/1994;67;78;89
Но это то, что вопрос хочет:
121212A Tan Ah Bee 72
031234F Michael Tan 72
123456J Abby 72
Я что-то упустил? Я знаю только, что это метод toString(), но я не знаю, как разместить его в цикле while.
Любая помощь будет оценена по достоинству. Заранее спасибо.
Вам не нужно печатать только что прочитанную строку (если вы не делаете ее для целей отладки). Вам нужно передать эту строку в ваш ** Constructor **, а затем распечатать результат вашего метода toString для этого вновь созданного экземпляра. –
Но я думал, что sc.nextLine равна studentRecord, и поэтому система будет автоматически использовать этот конструктор для разделения информации? И должен ли я использовать метод toString в основном методе? Можете ли вы, пожалуйста, дать мне пример? – Rauryn
Я изменил свой код на это: while (sc.hasNextLine()) { \t \t \t \t Студент-студент = новый студент (sc.nextLine()); \t \t \t \t System.out.println (student.toString());} Но есть ошибка исключения исключающего указателя. Я иду по неправильному пути? – Rauryn