这是我第一次来这里,我是编程的新手,我已经学习了2周的Java,我只知道一些基础知识,所以我决定通过做一个简单的文本冒险游戏而不使用对象来测试我的知识因为我还没有抓住那个。我将继续打印故事并描述情况,并接受玩家选择继续。 但我的代码有问题我不知道如果用户输入无效的选择如何重复问题,我尝试了几种方法,但程序结束或给我无限循环,我需要一些帮助,请
这是我的代码:
import java.util.Scanner;
class The_Crime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome Stranger, Please Enter Your Name");
String name = input.nextLine();
System.out.println("Welcome" + name);
Street street = new Street();
System.out.println("You are now in the street with a dead body on the floor drowned in blood \n there is a building right ahead of you\n What would you like to do?");
String choice = input.nextLine();
while(true) {
if(choice.equals("enter building")) {
System.out.println("You have entered the empty building");
} else {
System.out.println("You are now in the street with a dead body lying around drawned in blood \n there is a building right infront of you\n What would you like to do?");
}
}
}
}
答案 0 :(得分:1)
你的状态会永远持续下去,因为你永远不会break
。但在这种情况下你不需要改变
while(true)
if (choice.equals("enter building"))
System.out.println("You have entered the empty building");
else
System.out.println("You are now in the street with a dead body lying around drawned in blood \n there is a building right infront of you\n What would you like to do?");
到
while(choice.equals("some invalid choice"))
{
choice = input.nextLine();
}
或
while(!choice.equals("some valid choice"))
{
choice = input.nextLine();
}
答案 1 :(得分:1)
在这种情况下,我会建议使用do-while循环,在第一次问题时你必须要求,后来决定是基于选择
Scanner input = new Scanner(System.in);
String choice=null;
do{
System.out.println("What would you like to do?");
choice = input.nextLine();
}while(!choice.equals("enter building"));
我不确定您的确切要求,因此根据需要如此混乱,但我认为方法应该是在这里做的。
在你的情况下,while(true){ //Infinite loop }
没有提到破坏条件,这就是它无限的原因。
答案 2 :(得分:0)
while (true) {
System.out.println("You are now...");
String choice = Scanner.nextLine();
if (choice.equals("enter building")) break;
}
答案 3 :(得分:0)
问题是你永远不会改变循环中的选择值。基本上一旦他们做出选择,他们必须永远做出这样的选择。
choice = input.nextLine();
另外,你的循环将无限期地发生,因为它总是如此。您可能会中断以退出循环或使用变量来确定您的状态。
int state = 1;
while(state == 1) {
choice = input.nextLine();
if(choice.equals("leave")) {
state = 2;
System.out.println("Goodbye");
}
}
每个好游戏都有状态和某种有限状态机。
答案 4 :(得分:0)
替换
String choice = input.nextLine();
while(true)
if (choice.equals("enter building"))
System.out.println("You have entered the empty building");
else
System.out.println("You are now in the street with a dead body lying around drawned in blood \n there is a building right infront of you\n What would you like to do?");
与
while(!input.nextLine().equals("enter building")){
System.out.println("You are now in the street with a dead body on the floor drowned in blood \n there is a building right ahead of you\n What would you like to do?");
}