简体   繁体   中英

Generate list of random numbers starting with x

I was asked to generate a list of random numbers from 1 to 100. Then I was asked to print a message at each random number that was divisible by 7, that was okay too.

My issue is that this list has to start with the number 1 and has then to be continued with random numbers. Additionally, I want to print a certain text every fifth line.

Questions:

1) How do I start my list with the number 1 and still keep the rest random?

2) How do I print a message every fifth line?

I have been searching for 2 hours and only found results for python and other languages. I was not able to find the right answer.

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

        }
    }
}

The output I get is :

  • 3, 69, 75, 83, 96, 47, 7 : Lucky number!, 56, 30, 98, 6, 66, 97, 63, 14 : Lucky number!

The output I expect to get is:

  • 1, 3, 69, 75, 83 : message, 96, 47, 7 : Lucky number!, 56, 30 : message, 98, 6, 66, 97, 63, 14 : Lucky number!

Correct answer:

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("---");
            }
        }
    }
}

You can start the index of the loop from 2 instead of 1 and print out the number 1 before the for-loop. Something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM