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 :
The output I expect to get is:
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.