切换或If语句

时间:2016-05-13 23:18:03

标签: java if-statement switch-statement

我正在尝试编写一个让你在两件事之间做出选择的程序。 但在执行我选择的选项后,我希望能够返回相同选项的开头。

switch (option) {
case 1:
    System.out.println("Start of option 1");
    //option 1 will do things here
    System.out.println("End of option 1");
    //I want to return at the beginning of this case at the end of it
    break;

case 2:
    System.out.println("Start of option 2");
    //option 2 will do things here
    System.out.println("End of option 2");
    //I want to return at the beginning of this case at the end of it
    break;

default:
    break;
}

也可以选择退出所选案例。 另外,使用if语句来实现我正在尝试做的更容易吗?

1 个答案:

答案 0 :(得分:0)

case 2:
    case2sub();
default:
    break;
}
}

public static void case2sub() {
    System.out.println("Start of option 2");
    //option 2 will do things here
    System.out.println("End of option 2");
    //I want to return at the beginning of this case at the end of it
    boolean end = false;
    System.out.println("QUIT? (Y/N)");
    keyboardInput =  new Scanner(System.in).nextLine();
    if (keyboardInput.equalsIgnoreCase("Y"))
            end = true;
    else{}
    if (end){}
    else
        case2sub();
}

如果你把你的案例放在他们自己的方法中,你可以递归地调用它们,直到你输入一个exit语句。递归工作,while循环也是如此。

public static void case2sub() {
    boolean end = false;
    while (!end)
    {
    end = false;
    System.out.println("Start of option 2");
    //option 2 will do things here
    System.out.println("End of option 2");
    //I want to return at the beginning of this case at the end of it
    System.out.println("QUIT? (Y/N)");
    keyboardInput =  new Scanner(System.in).nextLine();
    if (keyboardInput.equalsIgnoreCase("Y"))
        end = true;
    }
}

您可以通过多种方式退出。这只是两个答案。

相关问题