Java printf formatting to print items in a table or columns

前端 未结 4 673
你的背包
你的背包 2021-01-19 17:24

I am wanting to print things in a neat columns using printf.

happening       0.083333    [4]
hi              0.083333    [0]
if              0.083333    [8]
         


        
4条回答
  •  误落风尘
    2021-01-19 17:56

    input:

    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]
    

    code:

    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();
          }   
      }
    

    output:

    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]
    

    use - to make the string left aligned, use field width to align them properly. In your case printf statement will be

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

提交回复
热议问题