作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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 的所有字母都被正确猜出时,退出 while 循环时遇到问题。非常感谢任何帮助。
最佳答案
只需在 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;
}
}
}
关于java - Hangman While 循环解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40983315/
我是一名优秀的程序员,十分优秀!