随机数生成器在一个范围内,然后打印序列的长度



我希望应用程序创建一个序列,该序列生成一系列从 0 到 9 的随机数,然后生成 0,然后显示数字序列的长度。现在我的程序只打印 0 或 9,因为我不知道随机数生成器方法。我的问题是我如何生成一个介于 0 和 9(含(之间的随机整数,单位 a 0 生成。

import java.util.Random;
import java.util.ArrayList;
public class Sequence {
   public static void main(String[] args) {
       ArrayList<Integer>  lista = new ArrayList<Integer>();
       lista.add(0, 9);

       Random r = new Random();
       System.out.println(lista.get(r.nextInt(lista.size())));
      }
   }

考虑使用 while-loop:

import java.util.Random;
class Sequence {
    public static void main(String[] args) {
        Random r = new Random();
        int count = 0;
        int num = -1;
        System.out.println("The sequence is:");
        while (num != 0) {
            num = r.nextInt(10);
            System.out.print(num + " ");
            count++;
        }
        System.out.printf("%nThe length of the sequence is: %d%n", count);
    }
}

示例输出:

The sequence is:
3 9 3 9 4 0
The length of the sequence is: 6

或者,如果需要将序列存储在集合中:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Sequence {
    public static void main(String[] args) {
        Random r = new Random();
        List<Integer> result = new ArrayList<>();
        int num = -1;
        while (num != 0) {
            num = r.nextInt(10);
            result.add(num);
        }
        System.out.printf("The sequence is: %s%n", result);
        System.out.printf("The length of the sequence is: %d%n", result.size());
    }
}

请考虑以下代码:

ArrayList<Integer> nums = new ArrayList<>();
Random r = new Random();
int num = r.nextInt(10);
while(num != 0)
{
    nums.add(num);
    num = r.nextInt(10);
}
System.out.println(nums.size());

要避免 List 因为 的第一个生成的随机数 0 而永远不会生成 num请考虑使用 if 语句并相应地重新分配值。

您当前的实现当前正在执行以下操作:

  1. 创建包含 1 个元素且值为 9
  2. 的列表
  3. 您对 Random 的调用的计算结果为 Random.nextInt(1) 将始终返回 0 作为参数,nextInt()是从 0 到该边界的独占上限。
  4. 简而言之,您的实现将始终返回列表中的第一项,即9

如果你想得到一个介于 0 和 9 之间的随机数,那么你需要调用上限为 10 的Random.nextInt(),即 Random.nextInt(10) .

要生成一个序列,您需要一个 while 循环,该循环在随机返回 0 时终止。

最后,由于您似乎不关心生成的序列以及您可以省去List的长度。

因此,您可以尝试如下操作:

    public static void main(String[] args) {
        Random r = new Random();
        int count = 0;
        while (r.nextInt(10) != 0) {
            count++;
        }
        System.out.println("Sequence Length = " + count);
    }

while 循环对此非常有用。检查您希望在生成 0 之前如何生成数字。当您希望某事一遍又一遍地发生直到满足条件时,请使用 while 循环。下面是一个 while 循环的示例,该循环将一直运行到生成 0:

ArrayList<Integer>  lista = new ArrayList<Integer>();
Random myRandom = new Random();
int next = myRandom.nextInt(10);
//We use 10 because nextInt() is non-inclusive for the upper bound. It will generate 0 to 9
while(next != 0) {
    lista.add(next);
    next = myRandom.nextInt(10)
}
lista.add(next); //When we get here, a 0 has been generated. Add it to the list.
//To display the length of the list, print out lista.size()
System.out.println(lista.size());

我假设您希望序列在生成 0 时停止,并且仍然将该 0 添加到列表中。如果没有,则在循环后排除 add(next(。

相关内容

最新更新