简体   繁体   中英

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:

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 . Therefore only the first index will be set with the random number. The others will keep their 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.

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

2 - Display the array

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

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

You can implement toString in BinaryArray

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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