java石头剪刀布while实现
时间: 2024-09-12 20:04:41 浏览: 50
石头剪刀布JAVA程序
在Java中实现"石头、剪刀、布"游戏的While循环版本,通常会涉及到用户输入判断以及随机电脑选择。下面是一个简单的示例:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random();
System.out.println("Let's play Rock-Paper-Scissors!");
while (true) {
System.out.print("Enter your choice (rock, paper, scissors): ");
String userChoice = input.nextLine().toLowerCase();
if (!("rock".equals(userChoice) || "paper".equals(userChoice) || "scissors".equals(userChoice))) {
System.out.println("Invalid choice! Please try again.");
continue;
}
// Generate a random computer choice
int computerChoice = random.nextInt(3);
String[] choices = {"rock", "paper", "scissors"};
String computerChoiceStr = choices[computerChoice];
System.out.println("Computer chose: " + computerChoiceStr);
// Determine the winner based on the rules
if ((userChoice.equals("rock") && computerChoiceStr.equals("scissors")) ||
(userChoice.equals("paper") && computerChoiceStr.equals("rock")) ||
(userChoice.equals("scissors") && computerChoiceStr.equals("paper"))) {
System.out.println("You win!");
} else if (userChoice.equals(computerChoiceStr)) {
System.out.println("It's a tie!");
} else {
System.out.println("You lose!");
}
// Ask for another round or quit
System.out.print("Do you want to play again? Type 'yes' or 'no': ");
String playAgain = input.nextLine();
if (!"yes".equalsIgnoreCase(playAgain)) {
break;
}
}
input.close();
}
}
```
在这个游戏中,玩家通过键盘输入选择,然后计算机随机出拳。程序会根据规则判断胜负,并询问是否再玩一轮。如果用户输入不是"yes",则退出游戏。
阅读全文