How can I create a java program which makes numbers align-right side?

My purpose is a java app that takes a number from a user. Start 1 and write it to console. Each new line series will increase 1 until the number token from the user. The important thing is to align each line to the right side.

    Scanner in = new Scanner(System.in);
    int numberOfLines = in.nextInt();

    for (int rows = 1; rows <= numberOfLines; rows++) {
        for (int i = numberOfLines - rows; i >= 1; i--) {
            System.out.print("  ");
        }
        for (int col = rows; col >= 1; col--) {
            System.out.printf(" %d",col);
        }
        System.out.println();
    }

                     1
                   2 1
                 3 2 1
               4 3 2 1
             5 4 3 2 1
           6 5 4 3 2 1
         7 6 5 4 3 2 1
       8 7 6 5 4 3 2 1
     9 8 7 6 5 4 3 2 1
   10 9 8 7 6 5 4 3 2 1
 11 10 9 8 7 6 5 4 3 2 1

when reaching double-digit numbers it is not right-aligned text. I tried to use the if condition in the loop but I could not do it.

Upvotes: 2

Views: 1190

Answers (3)

AB-san
AB-san

Reputation: 21

In order to make the 2 digits right aligned ,one of the ways would be- after the for loop of 'col' convert each digit to String then reverse it then after that print it . If u don't convert it to String then numbers like 10,20,30,etc would be printed as 1,2,3,etc

for (int rows = 1; rows <= numberOfLines; rows++) {
    for (int i = numberOfLines - rows; i >= 1; i--) {
        System.out.print("  ");
    }
    for (int col = rows; col >= 1; col--) {
      if(col>9){
        COL=Integer.toString(col);
        for(int i=COL.length();i>=0;i--)
        rev=rev+COL.charAt(i);
        System.out.printf(" %d",rev);
      }
      else
      System.out.printf("%d",col);
    
    }
    System.out.println();
}

Upvotes: 0

Idle_Mind
Idle_Mind

Reputation: 39122

Here's a different way to think about it using String concatenation.

You could generate the last row, first, to determine the maximum width that each row must be. Then for each row, you count backwards from the current row number down to 1 so you know the width of just the numbers part. Finally, you prepend the number of spaces needed to make the current row as wide as the last row. Note that is a horribly inefficient use of Strings, but really I'm demonstrating a different algorithm. Making this memory efficient would just make it harder to understand. Also note that the output being rendered correctly is dependent upon the environment in which you are running, and how it displays long strings. Some systems will add a scrollbar, while others may cause the strings to wrap.

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Number of rows? ");
    int numberOfLines = in.nextInt();

    if (numberOfLines >= 1) {
        int totalWidth = 0;
        // add up the widths of the numbers themselves
        for (int number = 1; number <= numberOfLines; number++) {
            totalWidth = totalWidth + ("" + number).length();
        }
        // add in the spaces in-between the numbers
        totalWidth = totalWidth + (numberOfLines - 1);

        // now generate each row by counting backwards from the current row number
        for (int rowNumber = 1; rowNumber<=numberOfLines; rowNumber++) {
            String row = "";
            for (int i=rowNumber; i>=2; i--) {
                row = row + i + " ";
            }        
            row = row + "1";

            // prepend the spaces in front to make it as wide as the last row
            int paddingLength = totalWidth - row.length();
            for(int i=1; i<=paddingLength; i++) {
                row = " " + row;
            }

            // output the row
            System.out.println(row);
        } 
    }
    else {
        System.out.println("Number of rows must be positive!");
    }
}

Sample output with 25 rows:

Number of rows? 25
                                                                1
                                                              2 1
                                                            3 2 1
                                                          4 3 2 1
                                                        5 4 3 2 1
                                                      6 5 4 3 2 1
                                                    7 6 5 4 3 2 1
                                                  8 7 6 5 4 3 2 1
                                                9 8 7 6 5 4 3 2 1
                                             10 9 8 7 6 5 4 3 2 1
                                          11 10 9 8 7 6 5 4 3 2 1
                                       12 11 10 9 8 7 6 5 4 3 2 1
                                    13 12 11 10 9 8 7 6 5 4 3 2 1
                                 14 13 12 11 10 9 8 7 6 5 4 3 2 1
                              15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
                           16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
                        17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
                     18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
                  19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
               20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
            21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
         22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
      23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
   24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Upvotes: 2

rzwitserloot
rzwitserloot

Reputation: 102872

Your code is doing the job just fine. The one problem you have, is that it stops working properly once you get to numbers that are more than 1 digit large: In your example, the 10 and the 11.

It's actually kind of tricky to fix that - what if I input '120392'?

You have a few options. Each option is more amazing, but also requires more code.

  1. Restrict your input. For example, disallow inputs beyond 99, and assume all numbers have a # of digits equal to the largest allowing numbers (so, 2 digits).
  2. Calculate the # of digits in the input, then assume all numbers have the calculated # of digits.
  3. Just get it right, with the spacing being applied increasing as numbers grow digits.

If you choose the first or second option, you'd get something like:

                                 1
                              2  1
                           3  2  1
                        4  3  2  1
                     5  4  3  2  1
                  6  5  4  3  2  1
               7  6  5  4  3  2  1
            8  7  6  5  4  3  2  1
         9  8  7  6  5  4  3  2  1
     10  9  8  7  6  5  4  3  2  1
 11  10  9  8  7  6  5  4  3  2  1

Note how this has way more spaces than your example (2 spaces in between e.g. every 4 and 3 instead of 1.

So, how? For #1 and #2, you need System.out.printf("%2d"); - this means: print a number, but if it takes fewer than 2 characters to do so, left-pad with spaces.

For #1 you hardcode the '2' (and hardcode a 99 limit; alternatively, hardcode 3 spaces, and a 999 limit). For #2 you get your input and then figure out how many digits that is. Something like String.valueOf(limit).length(); will do that, then you construct the format string using this length.

For #3 you track which number you're not printing in your System.out.print(" "); loop, so that you can still figure out how long the blank space you need to make has to be: If you're not printing a 10, you need 3 spaces. If you're not printing a 500, you'd need 4. If you're not printing a 5, you need 2.

For #2 and #3: printf("%4s", ""); prints 4 spaces. This is what you'd use to ask java to print X number of spaces. You're going to need this for solutions #2 and #3.

This sounds like first-week homework. I think #1 is most appropriate.

Upvotes: 2

Related Questions