我正在创建一个基于文本的游戏,到目前为止,我已经获得了,如果> else 语句要工作。但是,如果不起作用,则 else。我已经浏览了几个网站和几页,甚至与其他编码员进行了交谈。我已经尽力了,例如用 == 用>"?"。?")。我有 else 作为嵌套如果>,但也失败了。
public static void FirstRoom(){
System.out.println("You are in a room filled withndarkness and no memory of yournpast. There are several objectsnscattered on the ground and anlantern in your hand. You findna lighter in your pocket.");
System.out.println("n ----- n");
Scanner console = new Scanner(System.in);
String Call = console.next();
if (Call.equals("Inspect")) {
System.out.println("nYou can only see darkness");
System.out.println("n ----- n");
} else if(Call.equals("Light Lantern")){
System.out.println("nYou pull the lighter from your pocket and,nturning the knob, raise thenlantern's wick and light it.");
System.out.println("n ----- n");
}else{
System.out.println("nWhat do you mean?");
System.out.println("n ----- n");
FirstRoom();
}
String Call2 = console.next();
if(Call.equals("Inspect")) {
System.out.println("You see a large sword to yournright and a bag to the left.nThere is a door in frontn of you and a door behind.");
System.out.println("n ----- n");
}
}
当我输入 Light Lantern 时,我希望它会说您会从口袋里拉动打火机,然后转动旋钮,抬起灯笼的灯芯并点亮它。取而代之的是,它跳到第二个语句(也应该等待您输入第二个语句),并说您看到右边的一把大剑,左侧有一个袋子。您面前有一扇门,后面有一扇门。
Inspect
你只能看到黑暗
灯灯笼你看到一把大剑右,左边有一个袋子。前面有一扇门 你们和后面的一扇门。
您需要使用console.nextline()而不是console.next()
String Call /*bad name*/ = console.next();
只会采用第一个单词" Light"
String call = console.nextLine(); //using normal JAVA naming conventions
将把所有内容都带到线字符的末端,这意味着您将能够输入多个单词,例如"灯笼"
有关Next()和NextLine()之间差异的更多信息,您可以查看此帖子
您在检查Call
是否等于"Inspect"
之前停止在String Call2 = console.next();
处进行输入。您应该检查Call2
。
这将是我重新加工该方法的建议:
public static void FirstRoom() {
System.out.println("You are in a room filled withndarkness and no memory of yournpast. There are several objectsnscattered on the ground and anlantern in your hand. You findna lighter in your pocket.");
System.out.println("n ----- n");
Scanner console = new Scanner(System.in);
String Call;
boolean exitRoom = false;
boolean lantern = false;
while(!exitRoom) {
Call = console.nextLine();
if(Call.equals("Inspect") && !lantern) {
System.out.println("nYou can only see darkness");
System.out.println("n ----- n");
} else if(Call.equals("Light Lantern")) {
System.out.println("nYou pull the lighter from your pocket and,nturning the knob, raise thenlantern's wick and light it.");
System.out.println("n ----- n");
lantern = true;
} else if(Call.equals("Inspect") && lantern) {
System.out.println("You see a large sword to yournright and a bag to the left.nThere is a door in frontn of you and a door behind.");
System.out.println("n ----- n");
} else if(Call.equals("Leave")) {
System.out.println("You leave the room");
System.out.println("n ----- n");
exitRoom = true;
} else {
System.out.println("nWhat do you mean?");
System.out.println("n ----- n");
FirstRoom();
}
}
}
当请求离开房间的命令时,循环结束。