如何在 Java 中使用 printf() 格式化数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19849355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:40:52  来源:igfitidea点击:

How to format an array with printf() in Java?

javaprintf

提问by word word

I know how to format single variables, but I do not know how to format an array with printf(). I want to display my program with each number lining up with each other vertically, with each number on each line with the same amount of spaces. Below is an example of what I mean with different numbers:

我知道如何格式化单个变量,但我不知道如何用printf(). 我想显示我的程序,每个数字垂直排列,每行上的每个数字都有相同数量的空格。下面是我用不同数字表示的一个例子:

1.1   2.2   3.3   4.4   5.5
1     2     3     4     5

Here is the code that I have for trying to display the numbers:

这是我尝试显示数字的代码:

 // create array
 String[] tempsArray2 = temps2.toArray(new String[0]);

 // for-each loop
 for(String ss : tempsArray2){

     // display ss to make sure program works correctly
     System.out.printf("%40s", ss);

When I run it, the program displays like this:

当我运行它时,程序显示如下:

run:
70.3   70.8   73.8   77.0   80.7   83.4   84.5   84.4   83.4   80.2   76.3   72.0   
     69 67 66 64 66 69 67 67 70 69 69 70BUILD SUCCESSFUL (total time: 0 seconds)

How can I fix this so that I can format the whole array once with a single System.out.printf();statement, or do I have to format them one by one? Any help will be greatly appreciated.

我该如何解决这个问题,以便我可以用一条System.out.printf();语句格式化整个数组,还是必须一个一个地格式化它们?任何帮助将不胜感激。

回答by Jason C

If you want that specific control over formatting, you have to do it to each item individually. There is Arrays.toString(), but it provides no control over individual elements.

如果您想要对格式进行特定控制,则必须单独对每个项目进行控制。有Arrays.toString(),但它不提供对单个元素的控制。

If you are printing multiple arrays and you want their output to "line up", you will need to choose output formats so that happens, e.g.:

如果您要打印多个数组并且希望它们的输出“对齐”,则需要选择输出格式以便发生这种情况,例如:

    float data1[] = new float[] { 1, 2.5f, 30, 4.56f, 5 };
    int data2[] = new int[] { 1, 22, 33, -4, 5 };

    for (float f:data1) System.out.printf("%6.2f ", f);
    System.out.println();
    for (int n:data2) System.out.printf("%3d    ", n);
    System.out.println();

Which outputs:

哪些输出:

  1.00   2.50  30.00   4.56   5.00 
  1     22     33     -4      5  

That example might not be the precise format you are going for, but the point is, you have control this way. If you want to do left-aligned numbers, wider fields, if your types are Strings or floats or doubles or ints, etc.

该示例可能不是您想要的精确格式,但关键是,您可以通过这种方式进行控制。如果你想做左对齐的数字,更宽的字段,如果你的类型是字符串或浮点数或双精度数或整数等。

Sometimes it helps to work out field widths and padding spaces in e.g. a text editor or on paper first. E.g. with the above, where we try to line up decimal points and digits between floats and integers, I like to first work out the format in a fixed-width editor (like in a comment or in notepad), e.g.:

有时,首先在文本编辑器或纸上计算字段宽度和填充空间会有所帮助。例如,在上面,我们尝试在浮点数和整数之间排列小数点和数字,我喜欢首先在固定宽度的编辑器中(如在评论或记事本中)制定格式,例如:

FFF.FF FFF.FF FFF.FF FFF.FF
III    III    III    III

Then you can more easily see how that translates to format specifiers:

然后您可以更轻松地看到它如何转换为格式说明符:

  • FFF.FF is "%6.2f ".
  • III    is "%3d    ".
  • FFF.FF "%6.2f "
  • III    "%3d    "

See the documentation for Formatterfor more information about the format codes you can pass to System.out.printf().

有关Formatter可以传递给的格式代码的更多信息,请参阅文档System.out.printf()

回答by Alex Vallejo

Assuming you are working with a 2D array filled with doubles, you can do something like this to get nicely formatted output:

假设您正在使用填充双精度的二维数组,您可以执行以下操作以获得格式良好的输出:

double arr[][] = {
  {1.012,2.123,3.345,4.456,5.543,6.543,7.456,8.673,9.456,0.356},
  {1.133,2.135,3.456,4.654,5.234,6.067,7.456,8.432,9.235,0.959}
};

for (int row = 0; row < arr.length; row ++){
    for (int col = 0; col < arr[0].length; col++){
          System.out.printf("%-7.3f", arr[row][col]);
    }
    System.out.printf("\n");
}

The -aligns the numbers to the left and puts them all in nice columns. The 7is the field width and tells printf how wide to make your columns. The .3is the precision of the numbers (decimal places) that will print. Lastly, the f stands for float which is the format specifier for doubles. You can look up the syntax for java's printf in the docs.

-对齐的数字向左并把它们都在很好的列。这7是字段宽度并告诉 printf 使您的列有多宽。该.3是要打印的数字(小数)的精度。最后,f 代表浮点数,它是双精度数的格式说明符。您可以在文档中查找 java 的 printf 的语法。