简体   繁体   English

在Java中的对象内部打印数组

[英]Print an array inside of object in Java

I have a class and a constructor that fills an array with numbers and it sort it: 我有一个类和一个构造函数,用数字填充数组并对它进行排序:

public BinaryArray(int size){

    data = new int[size];
    for(int i:data){
        data[i] = 10 + generator.nextInt(90);
    }        
    Arrays.sort( data );
}

then in my other class where I have the main I want to print the array: 然后在我有主菜单的其他类中,我要打印数组:

BinaryArray searchArray = new BinaryArray( 15 ); //  create the Object

    for(BinaryArray i:searchArray){
        System.out.println( searchArray[i] );
    }

but its wrong.. I also code this but it prints sth else.. 但是它是错误的..我也编码了这个,但是它打印了其他。

BinaryArray searchArray = new BinaryArray( 15 );
System.out.println( searchArray );

Create a getter method in the class where you have the array: 在具有数组的类中创建一个getter方法:

public int[] getArray() {
    return data;
}

And then use that method in your main method: 然后在您的主要方法中使用该方法:

BinaryArray searchArray = new BinaryArray(15);
for (int i : searchArray.getArray()) {
    System.out.println(i);
}

Edit 编辑

Your constructor has a major bug: 您的构造函数有一个主要错误:

for(int i:data){
    data[i] = 10 + generator.nextInt(90);
}

i will always be set to 0 because every field in this array was initiliazed with 0 . i将始终设置为0因为此数组中的每个字段都初始化为0 Therefore only the first index will be set with the random number. 因此,只有第一个索引将被设置为随机数。 The others will keep their 0. 其他人将保持其0。

To fix that, use this loop instead: 要解决此问题,请改用以下循环:

for(int i = 0; i < data.length; i++){
  data[i] = 10 + generator.nextInt(90);
}

This should do it. 这应该做。

1 - Create a getter for the array. 1-为数组创建一个吸气剂。

public int[] getArray() {
 return data;
}

2 - Display the array 2-显示阵列

BinaryArray searchArray = new BinaryArray( 15 ); // create the Object

for(int i:searchArray.getArray()){
    System.out.println( i );
}

First thing, in the above code, i always equals 0, you have to iterate with an index 首先,在上面的代码中,我始终等于0,您必须使用索引进行迭代

data = new int[size];
for(int i:data){
    data[i] = 10 + generator.nextInt(90);
}

You can implement toString in BinaryArray 您可以在BinaryArray实现toString

public class BinaryArray
{
    private int[] data;

    public BinaryArray(int size)
    {
        data = new int[size];
        for(int i: = 0; i < size; i++){
            data[i] = 10 + generator.nextInt(90);
        }        
        Arrays.sort( data );
    }

   public String toString()
   {
       for (int i : data)
       {
            System.out.println(i);
       }
   }
}

And then 接着

BinaryArray searchArray = new BinaryArray( 15 );
System.out.println( searchArray );

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

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