生成以x开头的随机数列表

问题描述 投票:1回答:1

我被要求生成一个从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("---");
            }
        }
    }
}
java random numbers
1个回答
0
投票

您可以从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);
}
© www.soinside.com 2019 - 2024. All rights reserved.