Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Follow Instructions Carefully Create a file called ManyGreetings.java It should

ID: 3595814 • Letter: F

Question

Follow Instructions Carefully

Create a file called ManyGreetings.java
It should include a program that does the following:

Create a random number between 10 and 300 (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
Note: there is a separate line for each number from 1 to n (see output)
Hint: use the modulus operator ( % ) to determine whether "st", "nd", "rd", or "th" should be used

What is the Code in Java?

Sample output if n is 6:

1st greeting
2nd greeting
3rd greeting
4th greeting
5th greeting
6th greeting

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