[英]Breaking out of while loop in java
我真的不明白为什么它没有打破循环。 这是我的程序:
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;
}
}
}
你能告诉我这是怎么回事吗?
阅读开始后,您需要移动中断
start = input.nextDouble();
if (start == -1) {
break;
}
其他程序将继续运行,并且即使您输入-1也将在循环结束时中断
考试
if (start == -1) {
break;
}
应该在之后立即进行
start = input.nextDouble();
就您而言,您实际上是在退出while循环,但仅在执行循环主体之后才可以。
也要注意通过将start
声明为double
并随后使用==
测试其值而引入的可能问题。 对于此类变量,最好将其声明为int
。
将If块移到while循环之外。 它不会中断,因为当读取-1时,它无法进入if块的while循环。
将其移到外面,它将断裂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.