我被要求生成一个从 1 到 100 的随机数列表。然后我被要求在每个能被 7 整除的随机数处打印一条消息,这也可以。
我的问题是这个列表必须以数字 1 开始,然后以随机数字继续。另外,我想每五行打印一个特定的文本。
问题:
1) 如何以数字 1 开始列表并保持其余随机?
2) 如何每五行打印一条消息?
我搜索了2个小时,只找到了python和其他语言的结果。我找不到正确的答案。
import java.util.Random;
public class rannumb
{
public static void main(String[] args) {
Random rnd = new Random();
int number;
for(int i = 1; i<=100; i++) {
if (i%7==0) {
System.out.println(i+ " : Lucky number!");
}
number = rnd.nextInt(100);
System.out.println(number);
}
}
}
我得到的输出是:
- 3、69、75、83、96、47、7:幸运数字!、56、30、98、6、66、97、63、14:幸运数字!
我期望得到的输出是:
- 1, 3, 69, 75, 83:消息,96, 47, 7:幸运数字!, 56, 30:消息,98, 6, 66, 97, 63, 14:幸运数字!
正确答案:
public static void main(String[] args) {
Random rnd = new Random();
int number;
for(int i = 1; i<=100; i++) {
if (i==1) {
System.out.println(1);
continue;
}
number = rnd.nextInt(100);
//I used i instead of number first, thats why I had an issue
if (number%7==0) {
System.out.println(number+ " : Lucky number!");
}
else{
System.out.println(number);
}
// now I use i as you showed so that i can get the position of the number and not the number itself
if (i%5==0) {
System.out.println("---");
}
}
}
}
最佳答案
您可以从 2 而不是 1 开始循环索引,并在 for 循环之前打印出数字 1。像这样的东西:
Random rnd = new Random();
int number;
// print out 1 as you need it to be the first number
System.out.println(1);
// observe here that we start i at 2
for (int i = 2; i <= 100; i++) {
if (i % 7 == 0) {
System.out.println(i + " : Lucky number!");
}
if (i % 5 == 0) {
// Do something else here...
}
number = rnd.nextInt(100);
System.out.println(number);
}
关于java - 生成以 x 开头的随机数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55890962/