1

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

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

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

4

3 回答 3

7

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

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

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

于 2012-10-21T04:36:59.170 回答
4

考试

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

应立即完成

start = input.nextDouble();

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

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

于 2012-10-21T05:03:39.283 回答
0

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

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

于 2013-11-26T18:02:56.360 回答