如何让我的代码使用嵌套的if语句

时间:2015-12-12 14:37:21

标签: java if-statement netbeans

我正在用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.");
 }

Code Output

我可以输入开放式储物柜并且它有效但是当我输入世界历史时它不起作用它说你现在不能这样做...

2 个答案:

答案 0 :(得分:0)

  

我可以输入开放式储物柜并且它有效但是当我输入世界历史时它不起作用它说你现在不能这样做

这是因为您的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.");
     }
}

答案 1 :(得分:0)

您需要跟踪上次输入。让变量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.
 }

希望这会给你一点提示!!!

相关问题