随机产生一个单词,提示用户每次猜一个字母。单词中的每个字母以星号显示。当用户猜对一个字母时,显示实际字母。当用户完成一个单词时,显示猜错的次数,同时询问用户是否继续下一单词。单词存储使用数组形式,如:String[] words = {“write”,”that”,…}; java
时间: 2024-03-10 22:46:30 浏览: 138
好的,以下是一个简单的 Java 代码示例,实现了你描述的猜字母游戏:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessTheWord {
public static void main(String[] args) {
String[] words = {"write", "that", "java", "program", "computer", "science"};
Random random = new Random();
Scanner scanner = new Scanner(System.in);
boolean playAgain = true;
while (playAgain) {
// 随机选择一个单词
String word = words[random.nextInt(words.length)];
// 将单词转换为星号形式
char[] hiddenWord = new char[word.length()];
for (int i = 0; i < word.length(); i++) {
hiddenWord[i] = '*';
}
int wrongGuesses = 0;
boolean wordGuessed = false;
while (!wordGuessed) {
// 显示当前的单词状态
System.out.println("The word is " + new String(hiddenWord));
// 提示用户输入一个字母
System.out.print("Enter a letter in the word: ");
char guess = scanner.nextLine().charAt(0);
// 检查用户猜测的字母是否在单词中出现
boolean correctGuess = false;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == guess && hiddenWord[i] == '*') {
hiddenWord[i] = guess;
correctGuess = true;
}
}
// 如果猜测错误,则增加错误计数器
if (!correctGuess) {
System.out.println(guess + " is not in the word");
wrongGuesses++;
}
// 检查是否已经猜中了整个单词
wordGuessed = true;
for (int i = 0; i < hiddenWord.length; i++) {
if (hiddenWord[i] == '*') {
wordGuessed = false;
break;
}
}
}
// 显示游戏结果
System.out.println("You guessed the word " + word + " with " + wrongGuesses + " wrong guesses");
System.out.print("Do you want to play again? (y/n) ");
String answer = scanner.nextLine();
playAgain = answer.equalsIgnoreCase("y");
}
System.out.println("Thanks for playing!");
}
}
```
这个程序首先定义了一个字符串数组 `words`,包含了多个单词。然后,它使用 `Random` 类随机选择一个单词,将其转换为星号形式,并提示用户输入一个字母。每次用户猜测一个字母时,程序会检查该字母是否出现在单词中,如果是,则显示实际字母;如果不是,则增加错误计数器。当用户完成整个单词时,程序会显示猜错的次数,并询问用户是否要继续下一单词。
阅读全文