JAVA中用if else if else和do while 编程猜拳游戏
时间: 2024-04-04 13:28:00 浏览: 19
在Java中,可以使用if-else if-else语句和do-while循环来编写猜拳游戏。
首先,让我们来介绍一下if-else if-else语句。这种语句结构允许根据条件的不同执行不同的代码块。在猜拳游戏中,我们可以使用if-else if-else语句来判断玩家和电脑的出拳结果,并根据不同的情况给出相应的提示。
下面是一个简单的示例代码:
```java
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的选择(1-石头,2-剪刀,3-布):");
int playerChoice = scanner.nextInt();
// 生成电脑的选择(1-石头,2-剪刀,3-布)
int computerChoice = (int) (Math.random() * 3) + 1;
if (playerChoice == computerChoice) {
System.out.println("平局!");
} else if ((playerChoice == 1 && computerChoice == 2) ||
(playerChoice == 2 && computerChoice == 3) ||
(playerChoice == 3 && computerChoice == 1)) {
System.out.println("你赢了!");
} else {
System.out.println("你输了!");
}
}
}
```
接下来,让我们来介绍一下do-while循环。这种循环结构会先执行一次循环体中的代码,然后再根据条件判断是否继续执行循环。在猜拳游戏中,我们可以使用do-while循环来实现多次猜拳的功能,直到玩家选择退出游戏。
下面是一个简单的示例代码:
```java
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String playAgain;
do {
System.out.println("请输入你的选择(1-石头,2-剪刀,3-布):");
int playerChoice = scanner.nextInt();
// 生成电脑的选择(1-石头,2-剪刀,3-布)
int computerChoice = (int) (Math.random() * 3) + 1;
if (playerChoice == computerChoice) {
System.out.println("平局!");
} else if ((playerChoice == 1 && computerChoice == 2) ||
(playerChoice == 2 && computerChoice == 3) ||
(playerChoice == 3 && computerChoice == 1)) {
System.out.println("你赢了!");
} else {
System.out.println("你输了!");
}
System.out.println("是否继续游戏?(输入Y继续,其他键退出)");
playAgain = scanner.next();
} while (playAgain.equalsIgnoreCase("Y"));
}
}
```
以上就是使用if-else if-else语句和do-while循环编写猜拳游戏的示例代码。