我想格式化数字,以便它以正确的格式显示。目前 1-12 左侧除了 1 之外正确显示,因为由于将 8 插入格式,它已移动到另一个空间。
错误的结果如下所示......(-)在这里充当空格,因为我无法附加图像。
--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
我想要的结果如下所示......(-)在这里充当空格,因为我无法附加图像。
--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
如果有人能帮我解决这个问题,我很感激……一直让我发疯。
到目前为止,这是我的代码:
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);
}
}
}
最佳答案
您应该对单个元素应用格式:-
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.format()
转换为字符串变量,您可以稍后打印该字符串变量:-String result = String.format("%3d * %4d = %5d\n", numberLoop, num_input, result)
注意: - 有关更多格式选项 ,您可以查看 Formatter 的文档类..
关于java - 在 Java 中格式化输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12770222/