2

I want to format the numbers so that it gets displayed in proper format. At the moment 1-12 left side is displaying correctly apart from 1 because it has moved into another space due to pushing the 8 into the format.

The Wrong outcome is shown below... The (-) act as spaces on here because I cant attach an image.

--1 * 8 = -8
-2 * 8 = 16
-3 * 8 = 24
-4 * 8 = 32
-5 * 8 = 40
-6 * 8 = 48
-7 * 8 = 56
-8 * 8 = 64
-9 * 8 = 72
10 * 8 = 80
11 * 8 = 88
12 * 8 = 96

The outcome I want is shown below... The (-) act as spaces on here because I cant attach an image.

--1 * 8 = --8
--2 * 8 = 16
--3 * 8 = 24
--4 * 8 = 32
--5 * 8 = 40
--6 * 8 = 48
--7 * 8 = 56
--8 * 8 = 64
--9 * 8 = 72
10 * 8 = 80
11 * 8 = 88
12 * 8 = 96

I appreciate if anyone can help me with this... has been driving me insane.

Here is my code so far:

  public class Main {

        public static void main(String [] args) {

            int end_value = 13;
            int result = 0;

            System.out.print("Enter a Number:");
            int num_input = BIO.getInt();

            for (int numberLoop = 1; numberLoop < end_value; numberLoop++) 
            {
                result = numberLoop * num_input;

                System.out.printf("%11s\n", numberLoop + " * " + num_input + 
                                                          " = " + result);
            }
        }
    }
4

1 回答 1

3

您应该对单个元素应用格式:-

System.out.format("%3d * %4d = %5d\n", numberLoop, num_input, result);

你应该%d在打印整数时使用..

%3d将被替换numberLoop

%4d将被替换为num_input

%5d将被替换为result

你会得到如下输出: -

numberLoop(3 spaces) * num_input(4 spaces) = result(5 spaces)

%3d用于右对齐..%-3d用于左对齐.. 您可以使用其中任何一个..

您还可以使用将格式化的字符串存储到 String 变量中String.format(),以后可以打印该字符串变量:-

String result = String.format("%3d * %4d = %5d\n", numberLoop, num_input, result)

注意: - 有关更多格式化选项,您可以查看Formatter类的文档。

于 2012-10-07T15:44:49.820 回答