java - 数组和嵌套循环

标签 java arrays while-loop

书中的问题:

编写一个循环,用 1 到 100 之间的 10 个随机数填充数组值。为两个嵌套循环编写代码,用 1 到 100 之间的 10 个不同的随机数填充值。

我的问题:为什么这需要嵌套循环?

我的代码:

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

    }

}

最佳答案

请注意,您不需要仅仅为了使用数组而导入 Array。

您可以检查到目前为止数组中是否存在值 rnd,一旦发现重复的值,就递减外循环的计数器:

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

关于java - 数组和嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18857201/

相关文章:

java - 如何将资源指定为不翻译?

c - 为什么我在尝试传递数组值时收到 "incompatible pointer type"?

java - 如何编写并行数组

php - MySQL while循环查询在其他while循环查询中

c - 数组指针 while 循环输入

java - 设计问题: How to use composition the best

java - JPA的Hibernate实现

Java - 验证运算符

java - 如何在java中的while循环中添加?

arrays - 类 : how to find index in a method of the class 的 Swift 数组