aldangerduncan
aldangerduncan

Reputation: 49

Art & Science of Java Chapter 4, Exercise 8

I'm trying to write a program that does a countdown to liftoff, but using a while loop, instead of an for loop.

So far, all I succeed in doing is creating an infinite loop, even though I'm using the same basic principles as the for loop code.

import acm.program.*;



public class CountDownWhile extends ConsoleProgram {


    public void run() {
        int t = START;
        while (t >= 0); {
            println(t);
            t = t--;
            }
        println("Liftoff!");
        }

    private static final int START = 10;

    }

Upvotes: 0

Views: 578

Answers (2)

Bharat Sinha
Bharat Sinha

Reputation: 14363

The first problem is the ; after the while loop. Try removing the ;...

public void run() {
    int t = START;
    while (t >= 0); {  /// <------ Problem 1. Correct: while(t>=0)
        println(t);
        t = t--;       /// <------ Problem 2. Correct: t--;   
        }
    println("Liftoff!");
    }

and the second problem is

t=t--;

as the value of t remains unchanged.

Upvotes: 1

Rangi Lin
Rangi Lin

Reputation: 9451

There are two error in your code. And that's the reason you're getting an infinite loop

1.

while (t >= 0);

You shouldn't add a semi-colon after this line, because it is actually means a while loop with nothing in it.

2.

t = t--;

you can check this question to learn more about this syntax : Is there a difference between x++ and ++x in java?

In short, the value of t-- are still 10, so t = t-- dose not change the value of t.

The loop should look like this:

while (t >= 0) {
    println(t);
    t--;
}
println("Liftoff!");

Upvotes: 4

Related Questions