Java 程序并不是从头开始,尽管我试图告诉它

标签 java loops while-loop

基本上,我正在尝试使用 main 方法创建一个测试类。根据用户输入,程序应该遵循一定的步骤顺序,然后在最后,我试图让程序再次从头开始(即,在程序开头询问第一个问题) ,实际上不必退出程序并再次启动)。

我过去曾做过类似的事情,并且正在尝试以与以前相同的方式进行操作,但由于某种原因,这次不起作用。

这是我想做的事情的基本要点:

public class Payroll {
    public static void main(String[] args) {
        int steps = 0;

        while(steps == 0) {
        <Execute this code>
        steps = 1;
        }

        while(steps == 1) {
        <Execute this code>
        steps = 2;
        }

        while(steps == 2) {
        <Execute this code>
        steps = 0; //go back to the beginning
        }
    }
}

问题是,当程序到达“steps = 0”的步骤时,它会完全退出,而不是像我预期的那样回到开头。

有人知道如何做我想做的事情吗?

最佳答案

将三个 while 循环包含在另一个 while 循环中,从 while(steps == 0) 延伸到 while(steps = 的右大括号 } 之后= 2) .

如果您希望 steps == 2 循环控制流程,新的 while 循环可以具有条件 steps == 0。然后,您可以将步骤设置为 -1 以逃避封闭循环以及 steps == 2 循环。像这样:

while(steps == 0) {
    while(steps == 0) { /* ... */ }
    while(steps == 1) { /* ... */ }
    while(steps == 2) { /* ... */ } // this loop sets steps back to 0 to keep
                                    // looping, or it sets steps to -1 to quit
}

关于Java 程序并不是从头开始,尽管我试图告诉它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13835315/

相关文章:

c - 使用指针导航数组,而不是使用 int

php - 查询外部 while 循环,使用内部循环,不起作用

java - 无法执行多个 Spark 作业 "Initial job has not accepted any resources"

java - Android如何打包构建?

java - 将值绑定(bind)到 Guice 中的两种可能性之一

python - 使用 while 或 if 作为递归条件会导致不同的结果

php - 使用爆炸过滤数组

java - 哪种方法可以提供更好的性能?

java - Do-While 循环在程序运行时连续打印

arrays - 数组列表的实现