While loop ends even when the method is not called [Java]
我项目的一个需求是程序循环直到用户按下"X"键。我有这个方法,但即使不调用这个方法,程序也会终止。这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | while (terminate == false) { // Ask user for input switch (command) { case"I": { // Do stuff } case"X": { terminateProgram(); } } } |
这是我的终止方法:
1 2 3 4 5 | private static boolean terminateProgram() { terminate = true; return terminate; } |
即使我输入"i"键,循环也会在"i"的情况完成后结束。我"如果terminateProgram();被注释,则正常工作。只有当我输入"x"时,如何使循环停止?
在每个案例陈述中,您需要一个
读一下fall-through,这就是当前代码所做的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | while (!terminate) { // Ask user for input switch (command) { case"I": { // Do stuff break; } case"X": { terminateProgram() break; } default: // Do something default if no condition is met. } } |
然后在这里:
1 2 3 4 5 6 7 8 | private static void terminateProgram() { terminate = true; // if this method simply is to terminate a program // I'm not quite sure why you need a `terminate` variable // unless you're using it in another part of the program. // A simple system.exit(0) would suffice. System.exit(0); } |