Reputation: 7
The question is: write a method that is passed an int n
and returns a String
that counts down from n to 1. Ex countDown(3)
prints 321
My code is:
public class CountDown {
public static void main(String[] args) {
for(int n = n; n> 0; n--;) {
System.out.println("i=" + i);
}
}
}
I'm a beginner at coding but I'm not sure how to fix this. I believe my for loop is wrong.
Upvotes: 1
Views: 69
Reputation: 3782
The variable you declared in your for loop (n
) is different than the one you printed (i
), and you are assigning n
to n
when it is declared. You need to do this in order to make it work:
Either change the value of the variable in your for loop from n
to i
or print out n
instead of i
Change the declaration of the variable to not assign it to itself
Here is one way:
public class CountDown {
public static void main(String[] args) {
for(int i = 5; i > 0; i--;) {
System.out.println("i=" + i);
}
}
}
This will be the output:
i=5
i=4
i=3
i=2
i=1
Upvotes: 0
Reputation: 44952
In your current attempt you haven't declared n
variable and then re-declared it inside the for
loop which is not allowed.
You should declare a new countDown(int)
method and then use either while
or for
loop. It could look like:
public static void main(String[] args) {
System.out.println(countDown(3));
}
private static String countDown(int n) {
StringBuilder builder = new StringBuilder();
while (n > 0) {
builder.append(n);
n--;
}
return builder.toString();
}
Upvotes: 2