Java printf格式化,用于打印表或列中的项目

Java printf格式化,用于打印表或列中的项目,java,printf,multiple-columns,Java,Printf,Multiple Columns,我想打印的东西在一个整洁的列使用printf happening 0.083333 [4] hi 0.083333 [0] if 0.083333 [8] important 0.083333 [7] is 0.250000 [3, 5, 10] it 0.166667 [6, 9] tagged 0.083333

我想打印的东西在一个整洁的列使用printf

happening       0.083333    [4]
hi              0.083333    [0]
if              0.083333    [8]
important       0.083333    [7]
is              0.250000    [3, 5, 10]
it              0.166667    [6, 9]
tagged          0.083333    [11]
there           0.083333    [1]
what            0.083333    [2]
我有这个代码
System.out.printf(“%s%.6f%s\n”,word,web.getFrequency(word),loc),但它打印出以下内容:

happening  0.083333  [ 4 ] 
hi  0.083333  [ 0 ] 
if  0.083333  [ 8 ] 
important  0.083333  [ 7 ] 
is  0.250000  [ 3 5 10 ] 
it  0.166667  [ 6 9 ] 
tagged  0.083333  [ 11 ] 
there  0.083333  [ 1 ] 
what  0.083333  [ 2 ] 
任何帮助都将不胜感激。

我将使用以下方法:

System.out.printf ("%-30s %1.7f %s%n", word, etc, etc2);

您可以获取所有字串的最大长度,并将该长度存储在变量
max
中。使用for循环获取该
max
,然后创建一个
字符串
,该字符串的格式为将普通printf格式与用作宽度的max变量串联在一起。另外,
\t
放入制表符

int max = 0;
for (int ii = 0; ii < numberOfStrings; ii++)
{
   max = (word.length() > max) ? word.length() : max;
}
String format = "%" + max + "s\t%.6f\t%s \n";
System.out.printf(format, word, web.getFrequency(word), loc);
int max=0;
for(int ii=0;iimax)?word.length():max;
}
字符串格式=“%”+max+“s\t%.6f\t%s\n”;
System.out.printf(格式、word、web.getFrequency(word)、loc);
输入:

happening       0.083333    [4]
hi              0.083333    [0]
if              0.083333    [8]
important       0.083333    [7]
is              0.250000    [3, 5, 10]
it              0.166667    [6, 9]
tagged          0.083333    [11]
there           0.083333    [1]
what            0.083333    [2]
代码:

使用-要使字符串左对齐,请使用“字段宽度”将其正确对齐。 在您的情况下,printf语句将

System.out.printf("%-10s %.6f %s\n", word, web.getFrequency(word), loc);

将行填充到指定的宽度:可能重复:建议使用宽度和精度说明符,设置为相同的值(例如System.out.printf(“%-30.30s%-30.30s%n”,v1,v2);)。另请参阅以供参考:我不了解java,但在C中,这需要
\t
您可能需要在打印前检查每列的最大值
import java.util.Scanner;
public class MyClass { 
    private static final Scanner sc = new Scanner(System.in);
       public static void main(String args[]) {
            for(int i = 0 ; i < 9; i++){
                String str = sc.next();
                float f = sc.nextFloat();
                String str2 = sc.nextLine();
                System.out.printf("%-10s %f %s\n", str, f, str2);
             }
             sc.close();
      }   
  }
happening       0.083333    [4]
hi              0.083333    [0]
if              0.083333    [8]
important       0.083333    [7]
is              0.250000    [3, 5, 10]
it              0.166667    [6, 9]
tagged          0.083333    [11]
there           0.083333    [1]
what            0.083333    [2]
System.out.printf("%-10s %.6f %s\n", word, web.getFrequency(word), loc);