我正在尝试制作一个看起来像PC终端的基于文本的游戏,我找不到一种方法来告诉用户他们用错了句子


//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and 
repeat the command 
}

我几乎尝试了初学者所知道的一切,但什么都不做,在循环不起作用的情况下做(也许你能找到一种方法(,如果我这样做,如果你得到了错误的答案(一些不连贯的东西(,游戏就会结束,一些帮助会很棒!Thx:D

您可以使用"递归"函数(一个调用自身的函数(。

因此,在这种情况下,您可以执行以下操作:

public void getAndParseInput(){
String userInput = getUserInput() // Use whatever you're using to get input
if(userInput.contains(help)){ 
// If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
continueWithGame...
}else{
System.out.println("Im sorry , couldnt understand that");
this.getAndParseInput();
}
}

您需要将该代码放入while循环中,并建立退出条件。

boolean endGame = false;
/* Here read userinput */
While(!endGame) {
if (userinput.contains(help)) {
//Go on with the game
} else if(userinput.contains("quit"){
endGame = true;
} else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and 
repeat the command 
}
/* Here read userinput */
}

下面的代码与您的代码相似,根据需要进行适当的更改以重用代码。

代码的工作原理如下。
1。扫描控制台的输入
2。将扫描的输入与字符串"help"进行比较
3。如果扫描的输入与帮助匹配,则继续执行
4。否则,如果用户想继续,则可以按字母"C"并继续执行
5。如果用户未按"C",则控件会中断while循环并从执行中退出

public void executeGame() {
Scanner scanner = new Scanner(System.in);
String help = "help";
while(true) {
System.out.println("Enter the input for execution");
String input = scanner.nextLine();
if (input.contains(help)){
System.out.println("Continue execution");
} else {
System.out.println("Sorry Wrong input.. Would you like to continue press C");
input = scanner.nextLine();
if (input.equals("C")){
continue;
} else {
System.out.println("Sorry wrong input :"+input);
System.out.println("Hence Existing....");
System.exit(0);
}
}
}
}

相关内容