Home > other >  How to fix count down problem Java using counter
How to fix count down problem Java using counter

Time:04-27

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;
        }
    }

CodePudding user response:

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

CodePudding user response:

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.

  • Related