不会读取刽子手输入



我在java中有一个hangman赋值,我的大部分程序都能工作,除非它试图读取并保存输入。我只使用字符串,因为我不想把char转换成字符串

我的主菜:

public static void main(String[] args) 
{
    Scanner input = new Scanner(System.in);
    boolean active = true;
    do
    {
        startGame();
        do
        {
            System.out.println("You have "+(numGuesses)+" guesses left");
            drawBoard();
            System.out.println();
            System.out.println("Please enter your next guess: ");
            String mainGuess = input.nextLine();
            if ("stop".equals(mainGuess))
                currentState = End;//stops game if player chooses
            else
            {
                wordCondition(mainGuess);
                winLose();
            } 
        }
        while (currentState == Play);
        if (currentState == Win)
            System.out.println("Coongradulations you won!");  
        else if (currentState == Lose)
            System.out.println("Sorry, You lost");
        System.out.println("Would you like to play again? 1)yes 2)no");
        int answer=input.nextInt();
        active = (answer==1);
    }
    while (active);//creates a new game as much as user wants
}

和我的问题块

public static void wordCondition(String guess)
{
    if (guess.contains(word))//check if letter is in word and substitutes the letter
    {
        board[guess.indexOf(word)]=guess;
        total++;
    }

和我的绘图块

public static void drawBoard()
{
    System.out.println("Current word:");
    for(int i=0;i<word.length();i++)
        System.out.print(board[i]);
}

例如,单词是"name"我想要什么

你还有7个猜测当前单词:____请输入您的下一个猜测:

你还有7个猜测当前单词:_a__请输入您的下一个猜测:

我得到的

你还有7个猜测当前单词:____请输入您的下一个猜测:

你还有6个猜测当前单词:___请输入您的下一个猜测:

或类似的东西,格式有点不正确请帮助:)

这只是一个猜测,但代码不是错的吗?

public static void wordCondition(String guess)
{
    //check if letter is in word and substitutes the letter
    if (guess.contains(word))
        board[guess.indexOf(word)]=guess;
    else
        numGuesses--;
}

您正在检查输入的字母是否包含单词。你应该换一种方式检查:

public static void wordCondition(String guess)
{
    //check if letter is in word and substitutes the letter
    if (word.contains(guess))
        board[word.indexOf(guess)]=guess;
    else
        numGuesses--;
}

但这只会替换一个字母——如果有两个a,那么只有一个会被替换。你应该想想别的办法。

扰流板

您可以使用它来替换所有字母。但你真的应该使用char[]并为此改变你的方法:

public static void wordCondition(String guess)
{
    int position = 0;
    boolean found = false;
    for (char letter : word.toCharArray())
    {
        if (letter == guess.toCharArray()[0])
        {
            board[position]=guess;  
        }
        position++;
    }
    if (!found)
    {
        numGuesses--;
    }
}

相关内容

  • 没有找到相关文章

最新更新