0

I've been trying to have the console print this

1
22
333
4444
55555
666666

as

                1
               22
              333
             4444
            55555
           666666

I've tried using \t but that doesn't work.

4

5 に答える 5

3

Write the required number of space characters before you write the digits.

于 2012-11-09T05:32:19.373 に答える
2

Use String.Format

String formattedString = String.format("%" + spaceCount + "s", " "); 
//prints spaceCount spaces
System.out.println(formattedString); 

Increment space-count as necessary between lines, and you will get that many spaces.

于 2012-11-09T05:37:58.373 に答える
1

There's no good method for doing that, so you'll need to use spaces. But remember that console-windows aren't the same width everytime!

String number = /* Your number as string is needed here*/
String outcome = "";
int width = 15;
for(int i = 0; i < width - number.length; i++) {
    outcome += " ";
}
outcome += number;

It's bad method, but it should work. Repeat for each number you have.

于 2012-11-09T05:36:26.877 に答える
1

To use right-justification on the console, you have to know how far over you want it to be. Most terminals are 80 characters wide, so you could do:

String.format("%80d", i);

If you want less than that, use a number smaller than 80.

Using String.format makes java do all the counting work for you.

于 2012-11-09T05:37:42.973 に答える
1
for ( int i = 1 ; i <=6 ; i++ ){
            for( int j = 0 ; j <= 20 - i ; j++ ){
                System.out.print(" ");
            }
            int k = i ;
            while (k > 0){
                System.out.print(i);
                k--;
            }
            System.out.println("");
        }
于 2012-11-09T05:41:34.993 に答える