如果跳过/ else嵌套并转到下一个else语句

时间:2013-11-16 00:32:47

标签: java

在我的if / else语句中,我有两个if / else语句和两个嵌套的if / else语句。当我运行程序并输入“s”时,它将跳过第一个if语句然后跳转到第二个if语句并跳回到while循环并且永远不会到达嵌套的if / else语句。现在我打算让程序做的是当我输入“s”并且它运行第一个if语句时,理论上它应该通过嵌套的else语句运行,输出将是“你不能那样”。当我输入正确的输入“n”时,程序工作。有什么建议吗?

while(!input.equals("quit")) {
     System.out.println(map.rooms[row][col].name);
     System.out.print("<");
     input = scan.nextLine().toLowerCase();
     if (input.equals("n")) {      
         if (map.rooms[row][col].isValidExit("n"))
             row--;
         else
             System.out.println("There is no exit that way");
     } else if (input.equals("e")) {
         if (map.rooms[row][col].isValidExit("e"))
             row++;
         else
             System.out.println("There is no exit that way");
     }
}

2 个答案:

答案 0 :(得分:2)

很明显,当你的输入为's'时,程序永远不会到达嵌套的if / else语句,因为你的主if else语句只处理'n'情况和'e'情况,如果它想要处理其他情况并显示消息“没有退出那种方式”,那么你的代码应该是这样的:

while(!input.equals("quit")) {
 System.out.println(map.rooms[row][col].name);
 System.out.print("<");
 input = scan.nextLine().toLowerCase();
 if (input.equals("n")) {      
     if (map.rooms[row][col].isValidExit("n"))
         row--;
     else
         System.out.println("There is no exit that way");
 } else if (input.equals("e")) {
     if (map.rooms[row][col].isValidExit("e"))
         row++;
     else
         System.out.println("There is no exit that way");
 }
 else
 {
     // you should process other cases here like "s"
     System.out.println("There is no exit that way");
 }
}

答案 1 :(得分:0)

我认为你误解了条件分支的工作原理。

当你说

if (input.equals("n")
{
    System.out.println("go north");
}  
else if (input.equals("e")
{
    System.out.println("go east");
}

它将检查输入是否等于n,如果不是,它将检查下一个分支。它不会进入分支,即使它的计算结果为false,因为否则首先是条件分支的重点是什么?你不妨把它拿出来。

我认为你的“预期”逻辑也没有意义:如果用户点击“s”,为什么程序会检查north是否可以通过?从玩家的角度来看,你的设计似乎没有意义。

如果你想要一个“s”的案例,你可以将它作为另一个分支添加到用户输入“s”时

else if (input.equals("s"))
{
    System.out.println("go south");
}