在加利福尼亚州,每辆车牌照都包含3个字母。我们有一个游戏,其目标是制作一个字母。要获得与车牌匹配的单词,必须按顺序包含车牌中的所有字母 他们发生了什么。 KDN =开玩笑。 YRW =眉毛。你懂了。
所以我为这个游戏制作了一个代码并且它工作正常,只是它在找到输入的所有单词之后不会循环回到开头。我希望它能让我不必退出“运行窗口”并再次运行它,对于程序的每次运行。我试图找到这个bug,但我似乎无法找到我出错的地方。 非常感谢!还有,关于如何使这个程序更紧凑/更好的任何提示?
以下是代码:
import acm.program.*;
import java.io.*;
public class LicensePlateGame extends ConsoleProgram {
public void run(){
println("This program is the blueprint for the license plate game!");
while(true){
String letter = readLine("Enter three letters: ");
String letters = letter.toLowerCase();
try {
BufferedReader rd = new BufferedReader(new FileReader("dictionary.txt"));
// Breaks the input string apart to 3 characters
char one = letters.charAt(0);
char two = letters.charAt(1);
char three = letters.charAt(2);
while(letters.length() <= 3){
String line = rd.readLine();
// Finds the words that follow the game rules
if(line.indexOf(one) != -1 && line.indexOf(two) > line.indexOf(one) && line.indexOf(three) > line.indexOf(two)){
println(line);
}
}
println("Enter legit input");
}
catch (IOException x){
println("Error occured");
}
}
}
}
答案 0 :(得分:2)
这很糟糕:
while(letters.length() <= 3){
String line = rd.readLine();
// Finds the words that follow the game rules
if(line.indexOf(one) != -1 && line.indexOf(two) > line.indexOf(one) && line.indexOf(three) > line.indexOf(two)){
println(line);
}
}
while语句中,循环体中没有任何终止条件的组成部分发生变化,这就是灾难:它是一个无限循环。
是什么条件?当字典中的所有单词都被处理后停止!
String line;
while( (line = rd.readLine()) != null ){
if( line.length() >= 3 ){
if( line.indexOf... ){
System.out.println( line );
}
}
}
rd.close();
答案 1 :(得分:0)
以下是我的观察和建议。
似乎你的两个循环都是无限循环
对于第二个循环,你有一个条件,而你永远不会失败,你也不会在任何条件下中断循环。
第一步 - 在获得所需字词时添加中断。
while(letters.length() <= 3){
String line = rd.readLine();
// Finds the words that follow the game rules
if(line.indexOf(one) != -1 && line.indexOf(two) > line.indexOf(one) && line.indexOf(three) > line.indexOf(two)){
println(line);
break; // break when matching String found
}
}
但如果您的词典中包含与您的规则匹配的任何单词,则上述循环仍然可以是无限的。
第二步 - 当你阅读完整的词典
时出现循环 String line = null;
while(null!=(line = rd.readLine())){ // break when complete file has been read
if(line.indexOf(one) != -1 && line.indexOf(two) > line.indexOf(one) && line.indexOf(three) > line.indexOf(two)){
println(line);
break; // break when matching word found
}
}
FirstLoop while(true){
也将执行无限次,这不是一个好习惯。要终止此选项,请关闭此程序。
提议的解决方案: 您可以问用户您想继续游戏吗?读输入..如果输入是,则继续,否则你可以退出循环。 pseudoCode看起来像
String continueGame = "Yes"
while("Yes".equals(continueGame)){
// put your logic
continueGame = readLine("you want to play game again, enter Yes or No");
}
注意: -
关闭你的BufferedReader是非常重要的,更具体地说,在finally块中关闭它,这样就可以关闭所有条件。