简体   繁体   中英

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]+ " ");

    }

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM