简体   繁体   中英

Nested loop decrement number

Create a class that asks the user for a number, and then print out the following pattern based on the int input.

So the code I made result looked like this ...

12345 
 1234 
  123 
   12 

But it should look like this

    5
   45
  345
 2345
12345
Scanner tri = new Scanner(System.in);
System.out.println("Enter a postive integer.");
int shape = tri.nextInt();
for(int c = shape; c > 1; --c){
    for (int a = 1; a <= shape-c; a++){
        System.out.print(" ");
    }
    for(int d = 1; d <= c; d++){
        System.out.print(d);
    }
    System.out.println(" ");

Could you try this code below?

Scanner tri = new Scanner(System.in);
System.out.println("Enter a postive integer.");
int shape = tri.nextInt();

for (int c = shape; c >= 1; --c) {
    for (int a = 1; a <= c; a++) {
        System.out.print(" ");
    }
    for (int d = c; d <= shape; d++) {
        System.out.print(d);
    }
    System.out.println(" ");
}

// result
//     5 
//    45 
//   345 
//  2345 
// 12345 

Instead of using a nested loop, you can use some padding. Basically you need to have a string which consists of only spaces and is as long as the number of digits in your number.

In a loop take the substring of your number and fill the remaining with spaces. My code:

public static void pattern(int number)
    {
        String s=Integer.toString(number);
        String padding="";
        for(int i=0;i<s.length();i++,padding+=" ");
        for(int i=1;i<=s.length();i++)
        {
            System.out.println(padding.substring(i)+s.substring(s.length()-i));
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM