Your code is pretty well written, however as always there are things we can change, and other things that are good that I would like to point out.
Positives:
- You used a method. Dividing and conquering(although it seems small) is very important for shortening and simplifying code. It also prevents bugs.
- Your code is easy to read
Things to fix:
- It isn't good to give variables meaningless names. give them names like
line
rather than a
, or num
rather than n
.
- You indented 8 spaces after your
printNumber
method, rather than the usual suggested(and advised) 4 spaces.
- Instead of doing
return printNumber(n, a)
, simply call the method again, using printNumber(n, a)
. This makes the program just loop within that method.
If I were just to clean up your code and shorten it when applicable it would look like this:
public class JavaApplication2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int highestNum = scan.nextInt();
countDown(highestNum);
scan.close();
}
static int countDown(int highNum) {
int length = highNum;
if(length != 0) {
for(int i = length; i > 0; i--) {
System.out.print(i);
}
System.out.println();
highNum--;
countDown(highNum);
}
return 0;
}
}
Main changes to your code:
Made your main part the if
, rather than the else
. This removed the need for an else
completely. It keeps looping until line
is 0.
Simplified and shortened(a lot).
Changed names of method and variables.
There are many other simple ways to get the same output. Here's a very simple one using a for
loop:
public class JavaApplication2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
countDown(num);
scan.close();
}
static int countDown(int num) {
for(int i = num; i > 0; i--){
System.out.print(i);
}
num--;
System.out.println();
if(num != 0) {
countDown(num);
}
return 0;
}
}
This program prints the countdown until it is 0, then it starts a new line, decreases num
by one, and repeats.
Here's another way just using a double for
loop and no recursion.
public class JavaApplication2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
countDown(num);
scan.close();
}
static void countDown(int num) {
for(int height = num; height > 0; height--){
for(int index = height; index > 0; index--) {
System.out.print(index);
}
System.out.println();
}
}
}
This one prints index
until it is 0 num
times, decreasing every time.
The only reason I posted the other possibilities here is really just to prove no. there is no "most optimized" way of achieving this output. That's the beauty of programming, really. You can do the same thing 100,000 different ways. You can make this program using recursion, for-loops, and many other ways too, but they will all give the same output. The goal is to shoot for the cleanest, shortest, and most readable code. If you have any questions, please comment below.