这是我的问题。
(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);
}
}
这是info int text file的格式:
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循环中。
任何帮助将不胜感激。提前谢谢。
答案 0 :(得分:1)
你有:
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
您似乎需要:
while(sc.hasNextLine()){
Student stu = new Student(sc.nextLine());
System.out.println(stu.toString());
}
上面的代码将为类Student
调用构造函数,它将拆分该行并填充其字段。然后你的toString()方法将创建一个指定格式的输出字符串。