user3769297
user3769297

Reputation: 179

Issues with adding a random numbers to an array

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

Upvotes: 3

Views: 69

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201437

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

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44834

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

Upvotes: 2

Related Questions