1

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

3 Answers 3

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.