在java中打破while循环

时间:2012-10-21 04:33:12

标签: java loops while-loop

我真的不明白为什么它没有突破循环。这是我的计划:

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;
        }
    }
}

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

3 个答案:

答案 0 :(得分:7)

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

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

即使您已输入-1

,其他程序将继续并在循环结束时中断

答案 1 :(得分:4)

测试

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

应该在

之后立即完成
start = input.nextDouble();

在你的情况下,你实际上是在跳出while循环,但只是在执行循环体之后。

通过将start声明为double,然后使用==测试其值,也要注意可能出现的问题。对于这样的变量,最好将其声明为int

答案 2 :(得分:0)

在while循环外移动If块。它不会破坏,因为当它读取-1时,它无法进入if块的while循环。

将它移到外面会破裂。

相关问题