0

我正在尝试编写一个应用程序,该应用程序接受用户指定的数字,然后使许多对象(我称它们为学生)为它们分配一个随机名称和数字,然后对它们的数字进行排序。我已经解决了各种问题,但是在打印数组时遇到了问题。我的代码如下。我得到的输出是“新对象”我输入的次数,然后是我每个 toString 调用的“0:null”。任何帮助将不胜感激。谢谢你。

import java.util.Random;
import java.util.Scanner;

public class application {

public static void main(String[] args) {

    int studentSerialNumber;
    String studentName;

    System.out.println("Enter the number of students you would like to sort: ");
    Scanner scanner = new Scanner(System.in);
    int numOfStudents = scanner.nextInt();

    Student[] anArrayToSort = new Student[numOfStudents];

    for (int i = 0; i < anArrayToSort.length; i++) {

        studentSerialNumber = ((int)(Math.random() * 8888)) + 1000;
        studentName = getStudentName();

        anArrayToSort[i] = new Student(studentSerialNumber, studentName);

    }

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

    }
}

private static String getStudentName() {

    String studentName = "";
    int i = 7;
    Random r = new Random();

    while (i > 0) {
        char c = (char) (r.nextInt(26) + 'a');
        studentName = studentName + c;
        i--;
    }

    return studentName;
}
}


public class Student {

int studentSerialNumber;
String studentName;

Student(int studentSerialNumber, String studentName) {

    studentSerialNumber = studentSerialNumber;
    studentName = studentName;
    System.out.println("New Object");

}

public String toString() {
      return studentSerialNumber + ": " + studentName;
   }
}
4

1 回答 1

2

构造函数中的赋值不好:

Student(int studentSerialNumber, String studentName) {
    studentSerialNumber = studentSerialNumber;
    studentName = studentName;
    System.out.println("New Object");
}

这应该是:

Student(int studentSerialNumber, String studentName) {
    this.studentSerialNumber = studentSerialNumber;
    this.studentName = studentName;
    System.out.println("New Object");
}

目前,您正在为自己而不是Student实例字段分配值。

于 2013-04-07T15:49:09.670 回答