Create a file called ManyGreetings.java It should include a program that does th
ID: 3815152 • 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
Sample output if n is 6:
Explanation / Answer
//header files
import java.util.Random;
public class ManyGreetings{
//main function
public static void main(String[] args){
//initializing necessary variables and their values
int value;
Random rand = new Random();
int n = rand.nextInt(500) + 5;//generates random
for(int i =1; i<= n; i++)
{
value = i % 10;
if(value == 1 && i%11!=1){
System.out.println(i+"st greeting");//printing the output
}
else if(value == 2 && i%11!=2)
{
System.out.println(i+"nd greeting");//printing the output
}
else if(value == 3 && i%11!=3)
{
System.out.println(i+"rd greeting");//printing the output
}
else
{
System.out.println(i+"th greeting");//printing the output
}
}
}
}
Hope this helps
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.