3

I am trying to add random numbers to an empty array 20 numbers 0-99. When I run the code below it prints out 51 numbers and they are all 0.

Can someone please help me figure out what I am doing wrong here.

import java.util.Random;

public class SortedArray 
{

    int randomValues;
    int[] value;

    public SortedArray()
    {
    }


    public int getRandom()
            {
              Random random = new Random();
              for(int j=0; j<20; j++)
              {
                 randomValues = random.nextInt(100);
              }
              return randomValues;
            }

    public int getArray()
    {
        int result = 0;
        value = new int[randomValues];
        for(int item : value)
        {
            System.out.println("The array contains " + item);
        }
        return result;
    }

}

Here is my main method

public class ReturnSortedArray 
{
    public static void main(String[] args)
    {
        SortedArray newArray = new SortedArray();

        int random = newArray.getRandom();
        int array = newArray.getArray();
        System.out.println(array);
    }
}

2 Answers 2

2

In your method getArray

the code

value = new int[randomValues];

is simply creating a new empty int array of size ramdomValues.

As the default value of an int is 0, that is what you are getting

Also in your method getRandom you are setting the same value time and time again

for (...)
    randomValues = random.nextInt(100);

try

public int[] getRandomArr()
{
  int randomValues [] = new int [20];
  Random random = new Random();
  for(int j=0; j<20; j++)
  {
     randomValues[j] = random.nextInt(100);
  }
  return randomValues;
}
Sign up to request clarification or add additional context in comments.

Comments

0

I see a few issues, you should probably set the values in your constructor. You could also call it a set method (since it's not actually a get). Also, your getArray() doesn't return an array. So, I think you really wanted something like this,

public class SortedArray {
  private Random random = new Random();
  private int[] value = new int[20];

  public SortedArray() {
    super();
    setRandomValues();
  }

  public void setRandomValues() {
    for (int j = 0; j < value.length; j++) {
      value[j] = random.nextInt(100);
    }
  }

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

And then your main method, should be updated like

public static void main(String[] args) {
  SortedArray newArray = new SortedArray();

  int[] array = newArray.getArray();
  System.out.println(Arrays.toString(array));
}

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.