Asking for a natural number n, I want to print to the console in this format:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
.
.
.
n . . . 5 4 3 2 1
Inputting 4, this is what I have so far:
1
21
321
4321
I want to add a space between the numbers. This is my code:
import java.util.Scanner;
public class PatternTwo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userInput;
System.out.println("Please enter a number 1...9 : ");
userInput = in.nextInt();
String s="";
int temp = userInput;
for(int i=1; i<=userInput; i++ ) {
for (int k= userInput; k>=i; k-- ) {
System.out.printf(" ");
}
for(int j =i; j>=1; j-- ) {
System.out.print(j);
}
System.out.println("");
}
}
}
Add a space in front of the number to be printed and double the spaces above so that it is not a pyramid. Something like this:
import java.util.Scanner;
public class PatternTwo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userInput;
System.out.println("Please enter a number 1...9 : ");
userInput = in.nextInt();
String s="";
int temp = userInput;
for(int i=1; i<=userInput; i++ ) {
for (int k= userInput; k>i; k-- ) { // <- corrected condition
System.out.printf(" ");
}
for(int j = i; j>=1; j-- ) {
System.out.print(j);
// check if not 1 to avoid a trailing space
if (j != 1) {
System.out.print(" ");
}
}
System.out.println("");
}
}
}
EDIT
Thanks to /u/shash678 I corrected my solution to remove all unnecessary or wrong spaces
How about a cleaner solution, which avoids using nested for-loops:
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a number 1...9 : ");
final int n = scanner.nextInt();
final ArrayList<String> suffixes = new ArrayList<>();
for (int i = 1; i <= n; i++) {
suffixes.add(0, i + " ");
final String prefix = String.join("", Collections.nCopies(n - i, " "));
final String suffix = String.join("", suffixes);
System.out.println(prefix + suffix);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With