项目 4 多重选择功能菜单
-
请编写一个 Java 应用程序,给用户提供一个控制台功能菜单:计算两个数字的最大公
约数(GCD)、计算某个数字的阶乘(factorial)或者退出程序。请用 switch 语句实现这个菜单并
处理用户的选择。当用户选择其中的某个选项时,程序提供相应的功能。如果用户选择计算
最大公约数,则提示输入两个数字,然后计算并显示结果;如果用户选择计算阶乘,则提示
输入数字,然后计算并显示结果。每次计算完成后仍然显示功能菜单供用户选择直到用户选
择退出程序。如果用户选择了一个无效的菜单选项,程序将显示错误提示信息。 -
参考代码:
package ForthProject; import java.util.Scanner; public class LuoYu_4 { public static void main(String[] args) { System.out.println("Please choose an option:"); System.out.println("1 - Calculate Greatest Common Divisor(GCD)"); System.out.println("2 - Calculate factorial"); System.out.println("3 - Quit\n"); Scanner input = new Scanner(System.in); System.out.print("Choice:"); int num; while ((num = input.nextInt()) != -1){ switch (num) { case 1: gcd(); break; case 2: factorial(); break; case 3: System.out.println("Exiting program"); System.exit(0); break; default: System.out.println("\nThat is not a valid menu option,please choose again\n"); } System.out.println("Please choose an option:"); System.out.println("1 - Calculate Greatest Common Divisor(GCD)"); System.out.println("2 - Calculate factorial"); System.out.println("3 - Quit\n"); System.out.print("Choice:"); } } public static void gcd() { int gcd = 1, k = 2, num1, num2; Scanner input = new Scanner(System.in); System.out.print("Enter the first integer: "); num1 = input.nextInt(); System.out.print("Enter the second integer: "); num2 = input.nextInt(); while (k <= num1 && k <= num2) { if (num1 % k == 0 && num2 % k == 0) { gcd = k; } k++; } System.out.println("\nThe GCD of " + num1 + " and " + num2 + " is " + gcd + "\n"); } public static void factorial() { System.out.print("Please enter a number:"); Scanner input = new Scanner(System.in); int num = input.nextInt(); int factorial = 1; for (int i = 1; i <= num; i++) { factorial *= i; } System.out.println("\n" + num + "! " + " = " + factorial + "\n"); } }
-
结果显示:
Please choose an option: 1 - Calculate Greatest Common Divisor(GCD) 2 - Calculate factorial 3 - Quit Choice:1 Enter the first integer: 15 Enter the second integer: 78 The GCD of 15 and 78 is 3 Please choose an option: 1 - Calculate Greatest Common Divisor(GCD) 2 - Calculate factorial 3 - Quit Choice:2 Please enter a number:4 4! = 24 Please choose an option: 1 - Calculate Greatest Common Divisor(GCD) 2 - Calculate factorial 3 - Quit Choice:6 That is not a valid menu option,please choose again Please choose an option: 1 - Calculate Greatest Common Divisor(GCD) 2 - Calculate factorial 3 - Quit Choice:3 Exiting program Process finished with exit code 0