【问题标题】:Unable to print the array which is passed to the constructor [closed]无法打印传递给构造函数的数组[关闭]
【发布时间】:2021-02-06 12:36:14
【问题描述】:

问题是我需要打印对象的信息,包括包含学生分数的数组。但它反而会扔垃圾。数组也必须有 5 个元素

public class Student {
    Student(String fullname, int group, int marks[]){
        this.fullname = fullname;
        this.group = group;
        this.marks = marks;
    }//constructor
    void display(){
        System.out.println("Named: " + fullname + " | Group: " + group + " | Marks: " + marks);//prints out the objects
    }
    int group;
    int marks[];
    String fullname;//class fields
    public static void main(String[] args){
        Student Matthew = new Student("Whatever 1",14, new int[]{9, 6, 8, 4, 5});
        Student John = new Student("Whatever 2",13, new int[]{4, 9, 5, 10, 7});
        Student Max = new Student("Whatever 3",14, new int[]{7, 10, 8, 9, 9});//objects
        Matthew.display();
        John.display();
        Max.display();
    }
}

【问题讨论】:

标签: java arrays class oop constructor


【解决方案1】:

如果您不想使用Arrays.toString() 方法(出于美观原因),您可以使用该方法:

public static String arrayToString(int[] array) {
        String arrayString = "";
        for (int i = 0; i < array.length; i++) {
            arrayString += array[i] + ", "; // Write here whatever you want to separate the array elements
        }
        return arrayString;
    }

【讨论】:

  • 至少你可以使用 StringBuilder。这将不必要地产生大量垃圾。
【解决方案2】:

使用 Arrays.toString(marks) 打印数组值

public class Student {
    Student(String fullname, int group, int marks[]){
        this.fullname = fullname;
        this.group = group;
        this.marks = marks;
    }//constructor
    void display(){
        System.out.println("Named: " + fullname + " | Group: " + group + " | Marks: " + Arrays.toString(marks));
    }
    int group;
    int marks[];
    String fullname;//class fields
    public static void main(String[] args){
        Student Matthew = new Student("Whatever 1",14, new int[]{9, 6, 8, 4, 5});
        Student John = new Student("Whatever 2",13, new int[]{4, 9, 5, 10, 7});
        Student Max = new Student("Whatever 3",14, new int[]{7, 10, 8, 9, 9});//objects
        Matthew.display();
        John.display();
        Max.display();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多