简单的Java Hangman分配

时间:2011-02-14 01:32:50

标签: java

我为一个我们需要制作一个Hangman游戏但是一个真正的基础游戏(它是Java类的介绍)的类进行了Java任务。基本上我有一个人输入的单词而另一个人必须猜测这个单词,但是他们没有看到这个单词所以它显示它就像这样(如果这个单词是aardvark)

* * * * * * * *

然后用户输入一个字母,如果它的部分字符显示那些字母,例如:

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

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

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

所以......所以是的,我已经被困在这一段时间了,我真的需要帮助 感谢

P.S:这是一个介绍类,所以到目前为止我所知道的只是循环(for,while,do while etc),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 + "\"");

}

}

5 个答案:

答案 0 :(得分:5)

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

根据您的代码判断,您不需要任何有关用户输入的帮助,您唯一的问题是正确猜测正确替换星星,让我们来看看:

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

现在很酷的是:

  

......没有重复的信件......

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

  • 一种方法在字符串中找到第一个字符并输出其位置。由于你不接受重复的字母,这也是唯一的情况。
  • 另一种方法可以用另一个字符替换字符串内给定位置的字符。

我认为你可以轻松找到解决方案。请随时在评论中提出进一步的问题!

编辑:更多帮助

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)方法。循环可以完成这项任务。

答案 1 :(得分:3)

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

答案 2 :(得分:1)

存储与密码字长度相同的字符数组。将字符初始化为*,找到匹配项后,使用[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 + "\"");
}

答案 3 :(得分:1)

我将为您提供可以构建的代码的基本概念:

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);
        }
    }

}
}

答案 4 :(得分:-1)

如何创建HangMan游戏

  

package 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;
            }
        }
    }
}