Avo Koburyan
Avo Koburyan

Reputation: 11

Generating data for an array via Random class and sorting

Use the Random class to get numbers from 0 to 99 and store them into the array. Use a for loop to get each random number, store each into the array, and print each value.

Then use the bubble sort to sort the array, and print out the stored array.

here is my program

import java.util.Random;

public class Randomness
{
    public static void main(String[] args)
    {
        Random randomNum = new Random();
        for (int number = 0; number <= 99; ++number)
        {
            int num = randomNum.nextInt(100);

            System.out.print(num + " ");

            int numValues = num;
            int [] values = new int[numValues];

            boolean swap;
            do
            {
                swap = false;
                int temp;
                for (int count = 0; count < numValues-1; count++)
                    if (values[count] > values[count+1])
                    {
                        temp = values[count];
                        values[count] = values[count+1];
                        values[count+1] = temp;
                        swap = true;
                    }
            } while (swap);

            System.out.print(values[count] + " ");
        }
    }
}

i get error

System.out.print(values[count] + " "); array required, but Random found.

please help!

Upvotes: 1

Views: 2210

Answers (1)

Jon Lin
Jon Lin

Reputation: 143886

You aren't creating any random values in your array. You are creating an array of random length (between 0 to 99). You need to initialize each element of your array with a random:

    Random randomNum = new Random();
    int numValues = 100;
    int[] values = new int[numValues];
    for (int number = 0; number < numValues; ++number)
    {
        int num = randomNum.nextInt(100);
        System.out.print(num + " ");

        values[number] = num;
    }

Then do the bubble sort.

Upvotes: 3

Related Questions