当我键入特定单词时如何退出程序,在我的情况下"end"?



我遇到了问题。我目前正在为聊天机器人做一个学校项目。这是聊天机器人的游戏部分。这是一个单词争夺游戏。我可以输入错误的答案,程序会提示我重新输入答案。但是,如果我输入正确答案,程序就停在那里,程序没有停止。

我想做的是重复代码,就像继续玩游戏一样,直到我输入"end"这个词,但我不知道如何实现它。此外,大多数单词都在重复。例如,[动物]这个词通常会被打乱成[anialm]。

所以我也想在改进代码方面获得一些帮助。谢谢!!我还是一年级的学生,刚开始学习编程。

public static void main(String[] args) {
Scanner userinput = new Scanner(System.in);
String guess = "";
String scramble = "";
String[] questions = {"animal", "duck", "dinosaur", "butterfly", "dog", "horse", "cow", "cat", "elephant", "crocodile", "alligator"};
char charArr[] = null;
String wordToGuess = questions[new Random().nextInt(questions.length)];// questions[0]
for (int a = 0; a < wordToGuess.length(); a++) {
charArr = wordToGuess.toCharArray();  //0a 1n 2i 3m 4a 5l 6s
//generating a random number from the length of word to guess. Example: Animal, generated no = "1"
int rdm = new Random().nextInt(charArr.length);
//shuffling the words
char temp = charArr[a];     //charArr[0] is the letter "A" which is moved to temp
charArr[a] = charArr[rdm];  //A is then moved to charArr[rdm] which is index 1, so the word is currently "AAimals'
charArr[rdm] = temp;        //charArr[1] contains n which is then moved to temmp, which is 0, becoming nAimal
}
scramble = new String(charArr);
System.out.println("Your word is: " + scramble);
do {
while (!guess.equals(wordToGuess)) {
System.out.print(">>> ");
guess = userinput.nextLine();
if (!guess.equals(wordToGuess)) {
System.out.print(">>> ");
System.out.println("Please try again!");
} else {
System.out.println(">>> Great Job getting the answer!");
}
}
}while (!guess.equalsIgnoreCase("end"));
}
}

我认为首先要做的是重新构建您的代码,这将使调试更容易。

我想说的是,您的代码基本上要求分为两个部分:一个用于运行游戏,一个用于包含数据:

public class Anagram {
private String original= null;
private String scrambled = null;
public Anagram(String originalWord) {
this.original = originalWord;
this.scrambled = scramble(originalWord);
}
private String scramble(String original) {
//scramble logic here
return null;//your scrambled String
}
public boolean guess(String guess) {
return original.equals(guess);
}
}

然后我们将少担心很多,我们的运行循环基本上变成这样:

Anagram anagram = new Anagram(wordToGuess);
String input = null;
while (true) {
System.out.print(">>> ");
input = userinput.nextLine();
if (input.equalsIgnoreCase("end")) {
System.out.println("Unlucky, please come back again");
System.exit(0); 
}
if (anagram.guess(input)) {
System.out.println(">>> Great Job getting the answer!");
System.exit(0); 
}
else {
System.out.print(">>> ");
System.out.println("Incorrrect, please try again!");
}
}

这使用while(true)可以很容易地用其他类型的循环替换。

此外,通过将设置的代码提取到另一种方法可能会受益。

使用break;语句结束循环。

if(guess.equalsIgnoreCase("end")){
break;
}
if(guess.equalsIgnoreCase("end")){
System.exit(0);
}

相关内容