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?
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
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.
Be aware, as well, of the possible problem introduced by declaring start
as a double
and then testing its value with ==
. For such a variable, you should preferably declare it as an int
.
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.
Move it outside and it will break.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.