Write the code for a class called Compare. Within the class include the main() method which accepts three numbers from the user through the keyboard. The method will then compare and return the numbers to the user in descending order.
Answer
java
import java.util.Scanner;
/** * This class is solution for Week 3, 3.5 Code challenge 1 * It reads three integers from the user and prints them in descending order. * @author Jimmy * @version 1.0 */ public class Compare {
/** * This program takes three integer inputs and prints them in descending order. * It ensures valid integer input and uses Math functions to determine the order. * * @param args Command-line arguments (not used). */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the first number: "); int num1 = scanner.nextInt();
System.out.print("Please enter the second number: "); int num2 = scanner.nextInt();
System.out.print("Please enter the third number: "); int num3 = scanner.nextInt();
int min, mid, max; // Use if else structure to compare the size of three numbers if (num1 >= num2 && num1 >= num3) { max = num1; if (num2 >= num3) { mid = num2; min = num3; } else { mid = num3; min = num2; } } else if (num2 >= num1 && num2 >= num3) { max = num2; if (num1 >= num3) { mid = num1; min = num3; } else { mid = num3; min = num1; } } else { max = num3; if (num1 >= num2) { mid = num1; min = num2; } else { mid = num2; min = num1; } }
// Print descending order System.out.println("Numbers in descending order: " + max + " " + mid + " " + min);
// Close scanner scanner.close(); } }
Code challenge 2
Borrowing from your previous coding challenge, accept three numbers through the keyboard from the user. Using conditional operators, print the maximum number on the screen.
Answer
java
import java.util.Scanner;
/** * This class is the solution for Week 3, 3.6 Code challenge 2 * It reads three integers from the user and use conditional operators, print the maximum number on the screen. * @author Jimmy * @version 1.0 */ public class Compare { /** * This program takes three integer inputs from the user and prints the maximum number. * It uses conditional (ternary) operators to determine the largest value. * @param args Command-line arguments (not used). */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the first number: "); int num1 = scanner.nextInt();
System.out.print("Please enter the second number: "); int num2 = scanner.nextInt();
System.out.print("Please enter the third number: "); int num3 = scanner.nextInt();
// Using conditional operator to determine the maximum number int max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);
// Print the maximum number System.out.println("The maximum number is: " + max);