简体   繁体   中英

How can I make the numbers in this code right adjusted?

How do I make the numbers in my code right adjusted? Were should I insert the System.out.printf() and how do I use it? Also how can I make numbers left adjusted?

public class JTROLL
{
    public static void main(String[] Theory)
    {
        int k,i,j;

        System.out.print("The numbers are:"                                                );
        for (k = 0; k < 50; k++)
        {
            for ( i = k; i < 50; i++)
            {
                for ( j = i; j < 50; j++)
                {
                    if ( (k+1)*(k+1) + (i+1)*(i+1) == (j+1)*(j+1)                          )
                    {
                        System.out.println( "\n\t\t  " + (k+1) + ", "
                                                       + (i+1) + ", "
                                                       + (j+1)           );
                    }
                }
            }
        }
    }
}

The following should do the trick as you expect.

import java.util.Formatter;

final public class Main
{    
    public static void main(String[] args)
    {
        Formatter fmt = new Formatter();
        fmt.format("|%10.2f|", 123.123);
        System.out.println(fmt);

        fmt = new Formatter();
        fmt.format("|%10.2f|", 1.13);
        System.out.println(fmt);

        fmt = new Formatter();
        fmt.format("|%10.2f|", 152123.16777);
        System.out.println(fmt);

        fmt = new Formatter();
        fmt.format("|%10.2f|", 99.777);
        System.out.println(fmt);
    }
}

You may somewhat need to modify it to suit your format.


It produces the following output on the console.

|    123.12|
|      1.13|
| 152123.17|
|     99.78|
  1. Append your numbers and ", " separators to a StringBuilder.
  2. Find the length of your StringBuilder.
  3. Calculate how far right you need to shift your numbers.
  4. Put the appropriate number of spaces into a String.
  5. println(spacerString + myStringBuilder.toString());

There are lots of examples and explanatyions on formatting on http://docs.oracle.com/javase/tutorial/java/data/numberformat.html . To right adjust the integers use something like this:

System.out.println("The numbers are:");
for (k = 0; k < 50; k++) {
    for (i = k; i < 50; i++) {
        for (j = i; j < 50; j++) {
            if ((k + 1) * (k + 1) + (i + 1) * (i + 1) == (j + 1) * (j + 1)) {
                System.out.format("\t\t%3d,%3d,%3d%n", (k + 1), (i + 1), (j + 1));
            }
        }
    }
}

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