简体   繁体   English

通过构造函数传递数组

[英]Passing an array through a constructor

This is what I have so far: 这是我到目前为止:

import java.util.*;

public class SArray {

    private int[] array;

    public SArray(int a[]) {
        this.array = a;
    }

    public String toString() {
        String arrayString = "";
        int i = 0;
        while (i < array.length) {
            arrayString = arrayString + array[i];
            i++;
        }
        return arrayString;
    }

    public static void main(String[] args) {
        SArray tester = new SArray(new int[] { 23, 17, 5, 90, 12, 44, 38, 84,
                77, 3, 66, 55, 1, 19, 37, 88, 8, 97, 25, 50, 75, 61, 49 });
        tester.toString();
    }
}

I looked up how to pass arrays through a constructor and this is what I came up with but no values actually go into the array and Im wondering why? 我查找了如何通过构造函数传递数组,这就是我想出的但是没有值实际进入数组,我想知道为什么?

The values are going into the array but you're doing nothing with them. 这些值将进入数组,但您无法使用它们。 Probably you want/need to display the values, so use System.out.println 您可能希望/需要显示值,因此请使用System.out.println

public static void main(String[] args) {
    SArray tester = new SArray(new int[] {23, 17, 5, 90, 12, 44, 38, 84, 77, 3, 66, 55, 1, 19, 37, 88, 8, 97, 25, 50, 75, 61, 49});
    //now you're doing something with the value of toString
    System.out.println(tester);
}

The array is there... look: 阵列在那里......看:

public static void main(String[] args) {
        NewClass tester = new NewClass(new int[]{23, 17, 5, 90, 12, 44, 38, 84,
            77, 3, 66, 55, 1, 19, 37, 88, 8, 97, 25, 50, 75, 61, 49});
        for(int i = 0; i < tester.array.length; i++){
            System.out.println(tester.array[i]);
        }
    }

this is the output: 这是输出:

23, 17, 5, 90, 12, 44, 38, 84, 77, 3, 66, 55, 1, 19, 37, 88, 8, 97, 25, 50, 75, 61, 49,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM