繁体   English   中英

如何使我的代码与嵌套if语句一起使用

[英]How do I get my Code to work with nested if statements

我正在用Java创建一个交互式故事。 我正在使用Netbeans和Jswing来做所有的GUI。 当在其中嵌套另一个if语句时不允许使用参数...

if("Open Locker".equalsIgnoreCase(input)) {
     jLabel2.setText("You open your locker and tap your textbooks and they appear in your inventory. The warning bell rings.");
     jLabel3.setText("You remember your next class is World History...");

     if("Go to World History".equalsIgnoreCase(input)) {
          jLabel2.setText("You walk down the hallway realizing that you still have 45 minutes until");
          jLabel3.setText("class starts. You arrive in class and sit in your desk.");
     }
 }
 else {
     jLabel3.setText("You cannot do that right now.");
 }

代码输出

我可以输入打开的储物柜并且可以使用,但是当我输入进入世界历史记录不可用时,它表示您现在无法执行此操作...

我可以输入打开式储物柜,但可以,但是当我输入进入世界历史记录时,它不起作用,这表明您现在无法执行此操作

发生这种情况是因为您的input没有更改。 要进入第一个选项,您需要输入Open Locker ,然后输入第二个,您需要输入Go to World History ,但是您已经输入了一些内容。

您需要做的是在进入第一个if语句后要求其他输入:

if("Open Locker".equalsIgnoreCase(input)) {
     jLabel2.setText("You open your locker and tap your textbooks and they appear in your inventory. The warning bell rings.");
     jLabel3.setText("You remember your next class is World History...");

     //ask for input

     if("Go to World History".equalsIgnoreCase(input)) {
          jLabel2.setText("You walk down the hallway realizing that you still have 45 minutes until");
          jLabel3.setText("class starts. You arrive in class and sit in your desk.");
     }
}

您需要跟踪最近的输入。 让我们使用变量isLockedOpened来做到这一点

boolean isLockedOpened=false;

现在,如果更衣室处于打开状态,则设置isLockedOpened = true。 下次用户输入“转到世界历史记录”时,然后检查输入和isLockedOpened变量。 您的代码如下所示:

if("Open Locker".equalsIgnoreCase(input)) {
     //set locker opened
     isLockedOpened=true;
     jLabel2.setText("You open your locker and tap your textbooks and they appear in your inventory. The warning bell rings.");
     jLabel3.setText("You remember your next class is World History...");
 }else if("Go to World History".equalsIgnoreCase(input) && isLockedOpened=true) {
          jLabel2.setText("You walk down the hallway realizing that you still have 45 minutes until");
          jLabel3.setText("class starts. You arrive in class and sit in your desk.");
 }
 else {
     jLabel3.setText("You cannot do that right now.");
     //isLockedOpened=false;//you can set this to true or false but understand what will happen in both case.
 }

希望这会给您一点提示!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM