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

Modify the program to print \"1st\", \"2nd\", \"3rd\", \"4th\" and \"5th\" rathe

ID: 3689450 • Letter: M

Question

Modify the program to print "1st", "2nd", "3rd", "4th" and "5th" rather than "1th", "2th", etc., without introducing redundant statements (Hint: Precede the "if-else" statement with a separate if-else statement that determines the appropriate ending based on the number).

import java.util.ArrayList;
import java.util.Scanner;

public class MostPopularOS {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<String> operatingSystems = new ArrayList<String>();
int nthOS = 1; // User input, Nth most popular OS

// Source: Wikipedia.org, 2013
operatingSystems.add(new String("Windows 7"));
operatingSystems.add(new String("Windows XP"));
operatingSystems.add(new String("OS X"));
operatingSystems.add(new String("Windows Vista"));
operatingSystems.add(new String("Windows 8"));
operatingSystems.add(new String("Linux"));
operatingSystems.add(new String("Other"));

System.out.print("Enter N (1-7): ");
nthOS = scnr.nextInt();

if ((nthOS >= 1) && (nthOS <= 7)) {
System.out.print("The " + nthOS + "th most popular OS is ");
System.out.println(operatingSystems.get(nthOS - 1));
}

return;
}
}

Explanation / Answer

MostPopularOS.java


import java.util.ArrayList;
import java.util.Scanner;
public class MostPopularOS {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<String> operatingSystems = new ArrayList<String>();
int nthOS = 1; // User input, Nth most popular OS
// Source: Wikipedia.org, 2013
operatingSystems.add(new String("Windows 7"));
operatingSystems.add(new String("Windows XP"));
operatingSystems.add(new String("OS X"));
operatingSystems.add(new String("Windows Vista"));
operatingSystems.add(new String("Windows 8"));
operatingSystems.add(new String("Linux"));
operatingSystems.add(new String("Other"));
System.out.print("Enter N (1-7): ");
nthOS = scnr.nextInt();
String temp = "";
if ((nthOS >= 1) && (nthOS <= 7)) {
if(nthOS == 1){
       temp = "st";
   }
   else if(nthOS == 2){
       temp = "nd";
   }else if(nthOS == 3){
       temp = "rd";
   }else{
       temp = "th";
   }
System.out.print("The " + nthOS + temp+" most popular OS is ");
System.out.println(operatingSystems.get(nthOS - 1));
}
return;
}
}

Output:

Enter N (1-7): 5
The 5th most popular OS is Windows 8

Enter N (1-7): 2
The 2nd most popular OS is Windows XP

Enter N (1-7): 3
The 3rd most popular OS is Windows XP

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote