【问题标题】:Simple Java Hangman Assignment简单的 Java 刽子手作业
【发布时间】:2011-02-14 01:32:49
【问题描述】:

我被困在一个类的 java 作业上,我们需要制作一个 Hangman 游戏,但它是一个非常基本的游戏(它是 Java 类的介绍)。基本上我有一个人输入了一个词,而另一个人必须猜测这个词,但他们看不到这个词,所以它会像这样显示它,例如(如果这个词是土豚)

* * * * * * * *

然后用户输入一个字母,如果它是单词的一部分,则显示这些字母,例如:

输入字母:a
a a * * * a * *

输入字母:k
a a * * * a * k

输入字母:r
a a r * * a r k

还有一个……是的,我已经被困了一段时间了,我真的需要帮助 谢谢

P.S:这是一个介绍类,所以我目前只知道循环(for、while、do while 等)、if、if/else、switch 语句等。

import java.util.Scanner;

public class ass_2 {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    //  public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;

    int attempts = 10;
    int wordLength;
    boolean solved;
    Scanner userInput = new Scanner(System.in);


    System.out.println("OK Guessing Player ... turn around, while your friend enters the word to guess!\n");
    System.out.println("Other Player ‐ Enter your word (letters only, no repeated letters and not case sensitive):");

    String secretWord = userInput.next();


    // 20 blank spaces WITH a for loop, we're smart!
    for(int i = 1; i <= 20; i++)
        System.out.print("\n");


        Scanner userLetter = new Scanner(System.in);
        String letter;

        System.out.print("Word to date: ");
        for (int i = 0; i < secretWord.length(); i++)
        {
            System.out.print("*");
        }

        while (attempts <= 10 && attempts > 0)
        {
            System.out.println("\nAttempts left: " + attempts);
            System.out.print("Enter letter: ");

            attempts--;
        }

        System.out.println("\n---------------------------");
        System.out.println("Sorry you didn't find the mystery word!");
        System.out.println("It was \"" + secretWord + "\"");

}

}

【问题讨论】:

  • 到目前为止你有什么,你在哪里卡住了?
  • 我在原帖中添加了代码
  • 好的,太好了。你被什么困住了?
  • 您可能希望将您的类重命名为不包含单词“ass”的名称。我的教授们从不欣赏它:)
  • @Jordan:试着专注于你眼前的问题,而不是整个作业。所以问题是正确渲染当前单词。如果单词是 'hello' 并且还没有选择字母,它应该是 '*****'。如果,假设字母 'l' 是已知的,你想显示 '*ll;先尝试解决这个问题,然后再考虑其余的复杂性。一般来说,你应该把你的问题分解成更小的可管理的块,然后在最后把它们拼凑在一起。

标签: java


【解决方案1】:

嘿乔丹,你的第一次尝试看起来很不错!您只需要在 while 循环中添加更多逻辑来读取猜测并将“*”替换为正确的猜测。而且我建议您将混淆后的单词(“*****...”)也存储在一个字符串中,而不是仅仅打印出来,以后会很方便..

根据您的代码判断,您在用户输入方面不需要任何帮助,您唯一的问题是用正确的猜测正确替换星星,让我们开始吧:

String secret;
//read in secret string
String displaySecret;
//generate as many "*"s as secret is long and store them in displaySecret

现在很酷的是:

...没有重复的字母...

这将使您的任务更容易!查看 Williwaw 提供的 String 类的文档。在那里你会发现两种方法可以解决问题:

  • 一种方法是在字符串中查找第一次出现的字符并输出其位置。而且由于您不接受重复的字母,这也是唯一出现的情况。
  • 另一种方法可以将字符串中给定位置的字符替换为另一个字符。

我认为您会很容易找到解决方案。欢迎在 cmets 中提出更多问题!

编辑:更多帮助

String secret = "example-text";
String displaySecret = "";
for (int i = 0; i < secret.length(); i++)
    displaySecret += "*";

char guess;
//read in a guess
int position = secret.indexOf(guess);
//now position contains the index of guess inside secret, or
//-1 if the guess was wrong

String newDisplaySecret = "";
for (int i = 0; i < secret.length(); i++)
    if (i == position)
        newDisplaySecret += secret.charAt(i); //newly guessed character
    else
        newDisplaySecret += displaySecret.charAt(i); //old state

displaySecret = new String(newDisplaySecret);

该死的,我确定有某种 setCharAt(int) 方法.. 循环完成了这项工作。

【讨论】:

  • 我仍然不明白如何将星星放入 displaySecret 字符串中,我知道如何显示一颗星星然后只需使用 for 循环将其显示为单词长度的多次,但就是这样
  • @Jordan 你什么时候显示''?当输入的字符和之前输入的字符都不是字符时,“”将代替。另外,我什至没有注意到“......没有重复的字母......”>_
  • 我理解它的逻辑,但老实说我似乎无法将其编码大声笑所以如果用户输入的字符与单词中的字母不匹配,那么它会显示一个星号和然后如果它确实匹配,它将不做任何事情并显示原始字母,但它必须一次检查字符串中的每个字母,所以通过使用 for 循环
  • 好的,我试过你的代码,它确实有效(我确实改变了一些东西)但是由于某种原因它加倍了这个词,就像这个词是星号中的“鲍勃”它会显示 * ***** 非常感谢所有这些帮助!
  • 其实我刚刚想通了,我把 System.out.println 放在了循环中,这就是为什么它的长度增加了一倍,到目前为止还不错!现在我将尝试解决剩下的问题!
【解决方案2】:

这不是那么愚蠢,目的是让您更有能力提出原创解决方案。
例如,在这里,您正在使用字符串,因此可以继续查看 javadoc 并查看 the String page,看看是否有任何函数可以派上用场。
接下来是逻辑:你得到一个“String”输入,然后只得到“char”的输入,你必须将一个字符串与一个字符进行比较。因此,最好的方法是比较“字符串”的每个“字符”。
你不能使用数组?好的,您还可以使用循环和两个特定的字符串函数(您已经知道 length(),它是两者之一),这将给出与通过数组测试其每个元素相同的结果。
如果没有显示 * 或者没有剩余尝试,则游戏结束,因此只要这些条件都不为真,玩家就可以尝试。

【讨论】:

  • +1 我想为你的评论 +1,但它不见了,所以现在我要为你的答案 +1。希望我的回答没有提供太多帮助。
【解决方案3】:

存储一个与密码字长度相同的字符数组。将字符初始化为*,当找到匹配项时,使用[indexOf][1],显示找到的字符:

String secretWord = userInput.next();
int len = secretWord.length(); //Store the length which will be used to see if puzzle was solved.
char[] temp = new char[len]; //Store a temp array which will be displayed to the user
for(int i = 0; i < temp.length; i++) //initialize the array
{
    temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
    System.out.println("\nAttempts left: " + attempts);
    System.out.print("Enter letter: ");
    String test = userInput.next();

    if(test.length() != 1) 
    {
        System.out.println("Please enter 1 character");
        continue;
    }

    char testChar = test.charAt(0);

    //Find matches
    int foundPos = -2;
    int foundCount = 0; //How many matches did we find
    while((foundPos = secretWord.indexOf(testChar, foundPos + 1)) != -1)
    {
        temp[foundPos] = testChar; //Update the temp array from * to the correct character
        foundCount++;
        len--; //Decrease overall counter
    }

    if(foundCount == 0)
    {
        System.out.println("Sorry, didn't find any matches for " + test);
    }
    else
    {
        System.out.println("Found " + foundCount + " matches for " + test);
    }

    //Print 
    for(int i = 0; i < temp.length; i++)
    {
        System.out.print(temp[i]);
    }
    System.out.println();

    if(len == 0)
    {
        break; //Solved!
    }

    attempts--;
}

if(len == 0)
{
    System.out.println("\n---------------------------");
    System.out.println("Solved!");
}
else
{
    System.out.println("\n---------------------------");
    System.out.println("Sorry you didn't find the mystery word!");
    System.out.println("It was \"" + secretWord + "\"");
}

【讨论】:

  • 不使用数组可以做到吗?
  • @jordan 一切皆有可能,存储用户可见字符串的副本。但是为什么???
  • 给出答案并不能帮助新手学习如何找到答案。
  • 我们不允许使用数组进行赋值,这很愚蠢
【解决方案4】:

我将向您介绍可以构建的代码的基本概念:

public class HangMan {
public static void main(String[] args) {
    System.out.println("Enter Secrect Word");
    Scanner scn=new Scanner(System.in);
    String secrectStr = scn.next();
    StringBuilder b=new StringBuilder(secrectStr.length());
    for(int i=0;i<secrectStr.length();i++)
        b.append("*");
    char[] secrectStrCharArr=secrectStr.toCharArray(); 
    int charCnt=secrectStr.length();
    while(charCnt>=0){
        System.out.println("Secrect Word :"+b.toString());
        System.out.println("Guess a letter :");
        char guessChar = scn.next().toCharArray()[0];
        for(int i=0;i<secrectStrCharArr.length;i++){
            if(guessChar==secrectStrCharArr[i])
                b.setCharAt(i,guessChar);
        }
    }

}
}

【讨论】:

    【解决方案5】:

    如何创建 HangMan 游戏

    包 arr_game;

    import java.util.Random;
    import java.util.Scanner;
    public class HangMan3 {
        public static char[] star;
            public static void main (String args[])
            {   
                char game[];
                Scanner input = new Scanner(System.in);
                Random r = new Random();
                String[] arr = { "pakistan", "india", "jarmany", "america", "rashia", "iran", "iraq", "japan", "sudan", "canada"};
    
                String word = arr[r.nextInt(arr.length)];
                int count = word.length();
                char[] CharArr=word.toCharArray(); 
                char[] star = word.toCharArray();
            for(int i=0;i<star.length;i++)
            {
                star[i] = '*';
                System.out.print(star[i]);
            }
    
            for (int i=1; i<=3; i++)
            {
                System.out.printf ("\nGuess a Letter:");
                char letter= input.next().charAt(0);
    
                for (int j=0;j<CharArr.length; j++)
                {
                    if(letter == star[j])
                    {
                        System.out.println("this word already exist");
                    }
                    else
            {
                        if(letter==CharArr[j])
                        {
                            star[j]=letter;
                            i--;
                            System.out.printf("CORRECT GUESS!\n");
                        }
                    }
                }
                System.out.print(star);
                switch(i+0)
                {
                        case 1: System.err.printf("Strike 1\n");
                            break;
                        case 2: System.err.printf("Strike 2\n");
                            break;
                        case 3: System.err.printf("Strike 3\n");
                            System.err.printf("You're out!!! The word is Not_Matched\n");
                            break;
                }   
    
                System.out.printf("\n");
                if((new String(word)).equals(new String(star))) 
                {
                    System.err.printf("Winner Winner, Chicken Dinner!\n");
                    break;
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2018-10-20
      • 2017-03-09
      • 1970-01-01
      相关资源
      最近更新 更多