import java.util.*;
public class Hangman
{
public static void main(String[] args)
{
Scanner kybd = new Scanner(System.in);
System.out.println("Please enter word: ");
String Word = kybd.nextLine();
String dashWord = Word.replaceAll(".", "-");
System.out.println(dashWord);
StringBuilder dashWordB = new StringBuilder(dashWord);
System.out.println("Please guess a letter: ");
char letterGuess = kybd.next().charAt(0);
int lettersGuessed = 0;
// While loop should exit once letterGuessed is equal to Word.length()
while (lettersGuessed <= Word.length()){
for (int i=0; i < Word.length(); i++)
{
if (Word.charAt(i) == letterGuess)
{
dashWordB.setCharAt(i,letterGuess);
lettersGuessed++;
System.out.println("letters guessed: " + lettersGuessed);
System.out.println("word length: " + Word.length());
}
if (i == Word.length() - 1)
{
i = -1;
System.out.println(dashWordB);
System.out.println("Have another guess: ");
letterGuess = kybd.next().charAt(0);
}
}
}
System.out.println(dashWordB);
System.out.println(lettersGuessed);
}
}
当正确猜到dashWordB的所有字母时,在循环时退出时遇到问题。非常感谢任何帮助。
答案 0 :(得分:1)
只需在while循环中添加以下内容:
if(lettersGuessed == Word.length()){
break;
}
这应该可以帮助您解决问题。
另外,其他人建议将while条件更改为以下内容:
while (lettersGuessed < Word.length())
所以你的while循环应该如下:
while (lettersGuessed < Word.length()){
for (int i=0; i < Word.length(); i++)
{
if (Word.charAt(i) == letterGuess)
{
dashWordB.setCharAt(i,letterGuess);
lettersGuessed++;
System.out.println("letters guessed: " + lettersGuessed);
System.out.println("word length: " + Word.length());
}
if (i == (Word.length() - 1))
{
i = -1;
System.out.println(dashWordB);
System.out.println("Have another guess: ");
letterGuess = kybd.next().charAt(0);
}
if(lettersGuessed == Word.length()){
break;
}
}
}
答案 1 :(得分:0)
您的问题出在此处:while (lettersGuessed <= Word.length()){
只有lettersGuessed > Word.length()
或者您猜错的字母大于单词的长度时才会退出。
尝试while (lettersGuessed < Word.length()){