java 跳出java中的while循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12994994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:05:11  来源:igfitidea点击:

Breaking out of while loop in java

javaloopswhile-loop

提问by mewliat

I don't really see why it's not breaking out of the loop. Here is my program:

我真的不明白为什么它没有跳出循环。这是我的程序:

public static void main(String[] args) {

    Scanner input = new Scanner (System.in);

    double tution, rate, r, t, realpay, multiply, start;
    start = 0;

    while(start != -1)
    {
        System.out.print("Press 1 to start, -1 to end: ");
        start = input.nextDouble();

        System.out.print("Please enter the current tution fee for the year: ");
        tution = input.nextDouble();

        System.out.print("Enter in the amount of interest: ");
        rate = input.nextDouble();

        r = 1 + rate;

        System.out.print("Please enter the number of years: ");
        t = input.nextDouble();
        multiply = Math.pow(r,t);
        realpay = tution * multiply;

        System.out.println("the cost of your tution fee: " + realpay);

        if (start == -1)
        {
            break;
        }
    }
}

Could you tell me what is wrong with it?

你能告诉我它有什么问题吗?

回答by Amit Deshpande

You need to move break after reading start

阅读开始后你需要移动休息

start = input.nextDouble();
if (start == -1) {
    break;
}

Else program will continue and will break at the end of loop even if you have entered -1

否则程序将继续并在循环结束时中断,即使您输入了 -1

回答by Alexis Drogoul

The test

考试

if (start == -1) {
    break;
}

should be done immediately after

应该在之后立即完成

start = input.nextDouble();

In your case, you are actually breaking out of the while loop, but only after executing the body of the loop.

在您的情况下,您实际上是在退出 while 循环,但仅在执行循环体之后。

Be aware, as well, of the possible problem introduced by declaring startas a doubleand then testing its value with ==. For such a variable, you should preferably declare it as an int.

还要注意通过声明start为 adouble然后用 测试它的值可能引入的问题==。对于这样的变量,您最好将其声明为int.

回答by CuBonso

Move the If block outside the while loop. It wont break because when it reads -1 it cant get into the while loop to the if block.

将 If 块移到 while 循环之外。它不会中断,因为当它读取 -1 时,它无法进入 if 块的 while 循环。

Move it outside and it will break.

把它移到外面,它会坏掉。