Create a file called ManyGreetings.java It should include a program that does th
ID: 3818451 • Letter: C
Question
Create a file called ManyGreetings.java
It should include a program that does the following:
Create a random number between 5 and 500 (inclusive) and assign it to a variable called n
Print n greetings as described below.
1st greeting
2nd greeting
3rd greeting
4th greeting
...
Notice: each greeting is in a separate line and each line specifies whether this is the 1st, 2nd, ..
greeting
Important: avoid code repetition
Hint: use the modulus operator ( % ) to determine whether "st", "nd", "rd", or "th" should be used
Explanation / Answer
ManyGreetings.java
import java.util.Random;
public class ManyGreetings {
public static void main(String[] args) {
Random r = new Random();
String greeting = "greeting";
String temp= "";
int n = r.nextInt(500-5)+5;
for(int i=1; i<=n; i++){
if(i >=11 && i<=20){
temp = "th";
}
else{
if(i%10 == 1){
temp = "st";
}
else if(i%10 == 2){
temp = "nd";
}else if(i%10 == 3){
temp = "rd";
}else{
temp = "th";
}
}
System.out.println(i+temp+" "+greeting);
}
}
}
Output:
1st greeting
2nd greeting
3rd greeting
4th greeting
5th greeting
6th greeting
7th greeting
8th greeting
9th greeting
10th greeting
11th greeting
12th greeting
13th greeting
14th greeting
15th greeting
16th greeting
17th greeting
18th greeting
19th greeting
20th greeting
21st greeting
22nd greeting
23rd greeting
24th greeting
25th greeting
26th greeting
27th greeting
28th greeting
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.