首页 > 解决方案 > Java:格式化包含整数和数组的输出

问题描述

各位晚上好,

我正在为我的计算机科学期末考试尝试一些练习题,但在让我的输出与预期的完全匹配时遇到了一些麻烦。我不确定这是否是我的编译器的限制,或者我只是没有完全理解错误。

基本上,我得到了一个二维数组,我必须在每个向上计数的索引前面输出一个数字。我有,我的问题是输出格式不正确。

这应该是这样的:

在此处输入图像描述

这是它的样子: 在此处输入图像描述

我做了很多谷歌,我就是想不通。考虑到它需要的样子,我可以看出数字和字符串是右对齐的,因此对此进行了补偿,我还在每个字符串之后添加了一个制表符,以确保字符串和下一个整数之间的分隔。但是,由于某种原因,事情并没有完全正确对齐。

这是我的格式化输出代码:

int count = 0;

for (int i = 0; i < 5; i++) {
     for (int j = 0; j < 4; j++) {

          System.out.printf("%2d", count); //Prints each count, right aligned with a width of two.
          System.out.printf("%15s", seasons[i][j]); //Prints each season right aligned with a width of 15 
          // (largest String is 9 characters).
          System.out.printf("\t"); //Adds a tab after the previous season to align the next number.
          count++; //Increases count
     }

     System.out.println();
}

标签: javaformattingprintf

解决方案


推荐阅读