JAVA菜单设计程序,包括九九乘法表,猜数游戏
时间: 2024-02-23 10:58:03 浏览: 19
好的,我可以为您提供一个简单的JAVA菜单程序,其中包括九九乘法表和猜数游戏。以下是程序代码:
```java
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int choice;
do {
System.out.println("1. 九九乘法表");
System.out.println("2. 猜数游戏");
System.out.println("0. 退出程序");
System.out.print("请选择菜单项:");
choice = input.nextInt();
switch (choice) {
case 1:
multiplicationTable();
break;
case 2:
guessNumber();
break;
case 0:
System.out.println("程序已退出!");
break;
default:
System.out.println("无效的选择,请重新选择!");
break;
}
System.out.println();
} while (choice != 0);
}
public static void multiplicationTable() {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " × " + i + " = " + (i * j) + "\t");
}
System.out.println();
}
}
public static void guessNumber() {
Scanner input = new Scanner(System.in);
int answer = (int) (Math.random() * 100) + 1;
int guess;
int count = 0;
do {
System.out.print("请输入一个1到100之间的整数:");
guess = input.nextInt();
count++;
if (guess > answer) {
System.out.println("猜大了!");
} else if (guess < answer) {
System.out.println("猜小了!");
} else {
System.out.println("恭喜你猜对了!");
System.out.println("你猜了" + count + "次");
}
} while (guess != answer);
}
}
```
在这个程序中,我们使用了一个do-while循环来持续显示菜单,直到用户选择退出程序为止。然后,我们使用switch语句根据用户的选择来执行相应的操作。如果用户选择九九乘法表,我们则调用multiplicationTable()方法来打印九九乘法表。如果用户选择猜数游戏,我们则调用guessNumber()方法来进行游戏。如果用户选择退出程序,我们则打印一条退出消息。
multiplicationTable()方法使用两个嵌套的循环来打印九九乘法表。guessNumber()方法使用一个do-while循环来让用户猜数游戏,直到猜对为止。在每次循环中,我们使用if-else语句来检查用户的猜测是否正确,并相应地打印提示信息。
希望这个程序能帮助到您!