打印数组 - 重写toString()方法

时间:2014-11-20 18:11:37

标签: java arrays printing tostring

我有两个不同的班级,学生和学生考试 - 学生班有;

public class Student {

// Data Members 
private String name; // The name of this student
private long idNumber; // The ID number of this student

// Constructs a new Student with passed name and ID number parameters.
public Student(String studentName, long studentIDNumber) {
name = studentName;
idNumber = studentIDNumber;
}

// Returns the name of this student.
public String getName() {
return name;
}

// Returns the ID number of this student.
public long getIDNumber() {
return idNumber;
}

// Sets the name of this student.
public void setName(String studentName) {
name = studentName;
}

// Sets the ID number of this student.
public void setIDNumber(long studentIDNumber) {
idNumber = studentIDNumber;
}

@Override
public String toString(){
    return "Name: " + this.name;
}

} // end class

StudentTest类有3种不同的方法,1。要求用户输入数组的大小,然后创建一个类型为Student的数组,2。要求用户使用名称和ID号填充数组, 3.显示数组的内容。

import java.util.Scanner; 

public class StudentTest { 

// Main method.
public static void main(String [] args) {

    Student[] students = createArray();
    populateArray(students);
    displayArray(students);
}

// Method that asks user for size of array.
public static Student[] createArray() {

System.out.println("Enter size of array: ");
Scanner userInputEntry = new Scanner(System.in);
int inputLength = userInputEntry.nextInt();
Student students[] = new Student[inputLength];

return students; 

}

// Method that asks user to populate array.
public static void populateArray(Student [] array) {

    for(int i = 0; i < array.length; i++) {
        array[i] = new Student();
        System.out.println("Enter student name: ");
        Scanner userInputEntry = new Scanner(System.in);
        array[i].setName(userInputEntry.next());
        System.out.println("Enter student ID number: ");
        array[i].setIDNumber(userInputEntry.nextLong());
    }

}

// Method that displays contents of array.
public static void displayArray(Student[] array) {

    for(int i = 0; i < array.length; i++){
        System.out.println(array[i].toString());
    }

}

}

当我尝试运行它时,我收到有关

的错误
 array[i] = new Student();

在第二种方法的for循环中。

1 个答案:

答案 0 :(得分:3)

您希望如何运作?

@Override
public void toString(){
    return "Name: " + this.name;
}

它应该给你一个编译错误。您正在尝试发回字符串,返回类型为空。

将其更改为

@Override
public String toString(){
    return "Name: " + this.name;
}

将主要方法更改为

// Main method.
public static void main(String [] args) {
    Student[] students = createArray();
    populateArray(students);
    displayArray(students)
}