1

Why doesn't this for loop count the right number of times? If I set the variable runs to 3, the loops runs 4 times. (One extra case.)

Thanks in advance!

for (int i = runs; i >= 0; i--)
{
   System.out.println("Input Duration of Trip");
   Scanner timeCalc = new Scanner(System.in);
   System.out.print("Hours ==> ");
   int hour = timeCalc.nextInt();
   System.out.print("Minutes ==> ");
   int minute = timeCalc.nextInt();
   System.out.println("You entered: " + hour + " hour(s) and " + minute + " minutes");
   System.out.println();
   time = convertHoursMinutesToDouble(hour, minute);
   totalTime += time;
}

4 Answers 4

5

The loop runs for values:

3
2
1
0

That's 4 times.

If you want it to run for values 3, 2 and 1, you can change your for loop to:

for (int i = runs; i > 0; i--)

or

for (int i = runs; i >= 1; i--)
Sign up to request clarification or add additional context in comments.

Comments

1

Your mistake is in

i>=0

What the code is doing is going "Ok, i is going to be equal to three. Now, let's see, ok, back up again, subtract one, i =2... subtract one i=1... Now tricky tricky it SKIPS the termination part of the code because it looks at it first BEFORE substracting one so i=0, ok WAIT i=0 so STOP."

Solution?

for (int i = runs; **i >= 1**; i--)

This mistake always messes me up. Hope the whole "through the mind of the computer thing" doesn't bother you. That's how I tend to think.

Happy coding!

Comments

1
i == 3
i >= 0
println

i--
i == 2
i >= 0
println

i--
i == 1
i >= 0
println

i--
i == 0
i >= 0
println

That was 4 times. You need your condition to be: i > 0

Comments

0

Because you have set greater than or equal to...

So starts at 3 and goes, 2,1,0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.