user18960849
user18960849

Reputation:

How to fix count down problem Java using counter

I'm trying to create a code that uses a counter to countdown from int n. I'm able to count up just fine, but when I execute the code, it does not countdown at all. Does anybody know whereabouts I went wrong?

public void countUp(int n) {
        System.out.println("*** Counting up " + n);
        for (int step = 1; step <= n; step++) {
            System.out.println("counter = " + currentCount);
            currentCount += 1;
        }
    }
    public void countDown(int n){
        System.out.println("*** Counting down " + n);
        for (int step = 1; step >= n; step--){
            System.out.println("counter = " +currentCount);
            currentCount -= 1;
        }
    }

Upvotes: 0

Views: 99

Answers (2)

This is because countDown() function is not running at all because of the condition step>=n the condition is never satisfied unless n==1.

I don't know what value is exactly present in the variable currentCount considering it is n so just change the loop parameter to the following:-

for (int step = n; step >= i; step--)

Hope this help.

Upvotes: 0

Edwin M. Cruz
Edwin M. Cruz

Reputation: 462

public void countDown(int n){
    for (int step = n; step >= 0; step--){
        System.out.println("counter = " + step );
    }
}

Upvotes: 1

Related Questions