Java printf formatting to print items in a table or columns

前端 未结 4 639
你的背包
你的背包 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:48

    I would use this:

    System.out.printf ("%-30s %1.7f %s%n", word, etc, etc2);
    
    0 讨论(0)
  • 2021-01-19 17:54

    You can get the max length of all the word strings, and store that length in a variable, max. Use a for loop to get that max, and then create a String that has the format with concatenating the normal printf format with the max variable to be used as the width. Additionally \t puts in a tab character.

    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);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-19 18:07
    System.out.format("%-8s%-8s%-8s\n","a","b","pow(b,a)");
    System.out.format("%-8d%-8d%-8d\n",1,2,1);
    System.out.format("%-8d%-8d%-8d\n",2,3,8);
    System.out.format("%-8d%-8d%-8d\n",3,4,81);
    System.out.format("%-8d%-8d%-8d\n",4,5,1024);
    System.out.format("%-8d%-8d%-8d\n",5,6,15625);
    
    //the negative integer kinda sets it back to the number of space needed
    
    0 讨论(0)
提交回复
热议问题