Ali J. Ali J. - 26 days ago 5
Java Question

why is this do-while calculation is wrong?

When I enter 20 for current5, minuteCurrent should be 240, but do part keeps working even if minuteCurrent is over 240. Why? I tried so many more things, but they didn't help.

import java.util.Scanner;

class Person {

String name;
int heartRatePer5;
int current5;

void alarm() {

for (int i = 0; i < 3; i++)
System.out.print("!!! ");
System.out.println();
}

void stopAlarm() {
System.out.println("Alarm stopped");
}
}

public class App{
public static void main(String[] args) {

Person person1 = new Person();

Scanner input = new Scanner(System.in);

System.out.println("Enter the current heart rate per 5 seconds: ");
person1.current5 = input.nextInt();
int minuteCurrent = person1.current5 * 12;
// minuteCurrent = 0;

do {
System.out.println("Normalizing.");
person1.stopAlarm();
//minuteCurrent = input.nextInt();
break;
}

while (minuteCurrent < 220);

}


}

Answer

Do while loops work differently than while loops.

Notice the while loop condition is now moved to after the do while loop body. The do while loop body is always executed at least once, and is then executed repeatedly while the while loop condition is true.

See more here.

How can you fix it? Change your while loop to look like this:

while (minuteCurrent < 220) {
            System.out.println("Normalizing.");
            person1.stopAlarm();
            break;
}

Also, I have no idea why you are using a while loop. It would make a lot more sense to just use an if statement - it's the same thing as a while loop with a break at the end.