0

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(" ");
1
  • Your loop printing the numbers of a line always starts at 1 (for(int d = 1; ...), so why would you even expect it to print lines starting at a higher number? Commented Apr 12, 2019 at 2:56

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

I am basically formatting it (adding required number of spaces) using the padding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.