因此,对于一个班级,我们必须制作一个刽子手游戏,它可以接受用户输入的单词,然后让另一个人来解决它。它必须能够识别单词中的多个重复字母,否则我就完蛋了。下面是我的代码,它工作得很好,直到我删除了我的 checkformatch 方法中的 break 语句,以便它超越了最初发现的字母。有了中断,它永远不会找到第二个第三个等重复的字母,没有它,它会返回每个不是搜索到的字母的字母都是未命中的,并减少了我的生命计数。我需要的是一些关于如何在我的数组中搜索作为猜测输入的字母并返回它们在数组中的索引位置的提示,而不是认为数组中不是猜测的每个字符都是错误的输入。先感谢您。
package hangman;
import java.util.Scanner;
class Game {
int livesRemaining;
String letterGuessed;
String wordInput;
char[] hiddenWord;
char[] aOfWord ;
Scanner input = new Scanner(System.in);
boolean isFound;
int a;
public Game()
{
this.setLives(8);
//this.output();
System.out.println("Player 1 please enter the word to be searched: ");
wordInput = input.nextLine();
aOfWord = wordInput.toCharArray();
hiddenWord = new char[aOfWord.length];
for(int j = 0; j < hiddenWord.length; j++)
hiddenWord[j] = '*';
this.output();
while(livesRemaining > 0)
{
System.out.println("Please choose a letter: ");
letterGuessed = input.nextLine();
this.checkForMatch(letterGuessed);
if(isFound == true)
{
hiddenWord[a] = letterGuessed.charAt(0);
}
else
{
System.out.println("Is not found!");
this.reduceLives();
}
this.output();
}
}
public void setLives(int a)
{
this.livesRemaining = a;
}
public void reduceLives()
{
livesRemaining = livesRemaining -1;
System.out.println("Lives remaining: " + this.getLives());
}
public int getLives()
{
return livesRemaining;
}
public void output()
{
System.out.println("Lives remaining: " + this.getLives());
System.out.println("Word found so far ");
for(int i = 0; i < hiddenWord.length; i++)
{
System.out.print(hiddenWord[i] + "\n");
}
}
public void checkForMatch(String l)
{
for(int i = 0; i < aOfWord.length; i++)
{
//System.out.println("Comparing " + l.charAt(0) + " To " + aOfWord[i]);
if(l.charAt(0) == aOfWord[i])
{
isFound = true;
a = i;
break;
}
else
{
isFound = false;
}
}
}
}