我在java中有一个刽子手任务,我的大多数程序都工作,除非它试图读取输入并保存它。我只使用字符串,因为我不想把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]);
}
例如,单词是&#34; name&#34; 我想要什么
你还有7个猜测 当前字:_ _ _ _ 请输入您的下一个猜测: 一个
你还有7个猜测 当前字词:_ a _ _ 请输入您的下一个猜测:
我得到了什么
你还有7个猜测 当前字:_ _ _ _ 请输入您的下一个猜测: 一个
你还有6个猜测 当前字:_ _ _ _ 请输入您的下一个猜测:
或类似的东西,格式有点偏 请帮助:)
答案 0 :(得分:3)
这只是一个疯狂的猜测,但这不是代码错误吗?
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
则只会替换一个字母。你应该考虑其他一些方法来做到这一点。
<强> SPOILER 强>
您可以使用它来替换所有字母。但你应该真的使用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--;
}
}