이것은 내 질문입니다.ReadFile 및 분할 정보
(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);
}
}
그리고이 정보 INT 텍스트 파일의 형식입니다
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 루프 내에 배치하는 방법을 모른다.
도움을 주시면 감사하겠습니다. 미리 감사드립니다.
방금 읽은 행을 인쇄 할 필요는 없습니다 (디버깅 목적으로하지 않는 한). 이 줄을 ** 생성자 **에 넣고이 새로 생성 된 인스턴스에 대한'toString' 메서드의 결과를 출력해야합니다. –
하지만 sc.nextLine은 studentRecord와 같으므로 시스템이 해당 생성자를 자동으로 정보를 분할하는 데 사용합니까? 그리고 나는 main 메소드에서 toString 메소드를 사용하기로되어 있나? 친절하게 제게 몇 가지 예를 들어 주시겠습니까? – Rauryn
코드를 다음과 같이 수정했습니다. while (sc.hasNextLine()) { \t \t \t \t 학생 학생 = 신입생 (sc.nextLine()); \t \t \t \t System.out.println (student.toString());}하지만 null 포인터 예외 오류가 있습니다. 나는 잘못된 길로 가고 있니? – Rauryn