Can't see me
Can't see me

Reputation: 501

Arrays and nested Loops

Question in book:

Write a loop that fills an array values with ten random numbers between 1 and 100. Write code for two nested loops that fill values with ten different random numbers between 1 and 100.

My question: Why does this require a nested loop?

My code:

import java.util.Arrays;
import java.util.Random;

public class ArrayPractice
{
    public static void main(String[] args)
    {
        Random random = new Random();
        int[] a = new int[10];
        int i;

        for (i = 0; i < 10; i++)
        { 

            a[i] = 1 + random.nextInt(100);

            System.out.print(a[i]+ " ");

    }

}

Upvotes: 1

Views: 2828

Answers (2)

Igor B
Igor B

Reputation: 76

import java.util.Arrays;
import java.util.Random;

public class ArrayPractice {
    public static void main(String[] args) {
        Random random = new Random();
        int[] array = new int[10];
        int index = 0;

        while(index < array.length){
            int number = 1 + random.nextInt(100);

            boolean found = false;
            for (int i = 0; i < index; i++) {
                int elm = array[i];
                if (elm == number) {
                    found = true;
                    break;
                }
            }
            if(!found){
                array[index++] = number;
            }
        }
        System.out.print(Arrays.toString(array));
    }
}

Upvotes: 1

user unknown
user unknown

Reputation: 36229

Note that you don't need to import Array just for using arrays.

You can check for existing values rnd in the array so far, and decrement the counter of the outer loop, as soon as you find a value repeated:

import java.util.Random;

public class ArrayPractice
{
    public static void main(String[] args)
    {
        Random random = new Random();
        int[] a = new int[10];

        for (int i = 0; i < 10; i++)
        { 
            int rnd = 1 + random.nextInt (100);
            a[i] = rnd;
            System.out.print (a [i] + " ");
            for (int j = 0; j < i; ++j)
            {
                if (a[j] == rnd) --i;
            }
        }
    }
}

Upvotes: 1

Related Questions