书中的问题:
编写一个循环,用 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/