Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with adding a random numbers to an array

Tags:

java

arrays

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);
    }
}
like image 443
user3769297 Avatar asked Aug 31 '26 07:08

user3769297


1 Answers

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;
}
like image 199
Scary Wombat Avatar answered Sep 02 '26 22:09

Scary Wombat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!