gpt4 book ai didi

java - 基本 Java 刽子手

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:23:04 27 4
gpt4 key购买 nike

我刚刚开始学习 Java 作为我的第一门编程语言。

在类里面,我们被分配使用 while 和 for 循环制作一个基本的 Hangman 游戏。

到目前为止我有什么

当用户输入第一个猜测时,它确实识别出他/她猜测的字符已被纠正,但只是继续并指出我猜错了一个字母!

帮助将不胜感激!!我的问题是我的代码做错了什么?我需要程序来告诉用户他的猜测是对还是错。

我的代码:

import cs1.Keyboard;

public class Hangman {
public static void main(String args[]) {
int guessCount = 0;
int correctGuess = 0;
boolean foundIt;
boolean solved;
char guess, answer;
String word;

System.out.println("Welcome to HangMan!");
System.out.println("Please enter a word for the opponent to guess!");
word = Keyboard.readString();
while (guessCount <= 6) {
System.out.println("Please enter any letter A-Z as your guess!");
guess = Keyboard.readChar();
for (int i = 0; i < word.length(); i++) {
if (guess == word.charAt(i)) {
System.out.println("You have guessed a correct letter!");
correctGuess++;
System.out.println("Correct Guess Count: "
+ correctGuess);
solved = false;
}
else if (guess != word.charAt(i)) {
System.out.println("Sorry! That is an incorrect guess! "
+ "Please try again!");
guessCount++;
System.out.println("Guess Count: " + guessCount);
solved = false;
}
}
if (correctGuess == word.length()) {
solved = true;
System.out.println("Congratulations! " +
"You have guessed the word!");
}
}
}
}

这是我目前所拥有的,这是输出

Welcome to HangMan!
Please enter a word for the opponent to guess!
hello
Please enter any letter A-Z as your guess!
l
Sorry! That is an incorrect guess! Please try again!
Guess Count: 1
Sorry! That is an incorrect guess! Please try again!
Guess Count: 2
You have guessed a correct letter!
Correct Guess Count: 1
You have guessed a correct letter!
Correct Guess Count: 2
Sorry! That is an incorrect guess! Please try again!
Guess Count: 3
Please enter any letter A-Z as your guess!

最佳答案

您将猜测String 中的每个字符进行比较,然后针对每个字符显示消息。相反,您应该编写一个方法来返回与输入匹配的字符数(这也处理具有重复字母的单词)。所以,

private static int countOf(String in, char ch) {
int count = 0;
for (char c : in.toCharArray()) {
if (c == ch) {
count++;
}
}
return count;
}

然后你可以这样调用它,

guess = Keyboard.readChar();
int count = countOf(word, guess);
if (count > 0) {
System.out.println("You have guessed a correct letter!");
correctGuess += count;
} else {
System.out.println("Sorry! That is an inncorrect guess! Please try again!");
}
guessCount++;

编辑 要在没有第二种方法的情况下进行编辑,您可以使用,

guess = Keyboard.readChar();
int count = 0;
for (char c : in.toCharArray()) {
if (c == guess) {
count++;
}
}
if (count > 0) {
System.out.println("You have guessed a correct letter!");
correctGuess += count;
} else {
System.out.println("Sorry! That is an inncorrect guess! Please try again!");
}
guessCount++;

而且,由于您还没有使用 for-each -

char[] chars = in.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == guess) {
count++;
}
}

关于java - 基本 Java 刽子手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26269532/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com