2009-03-31 11 views

答えて

48

同じ値に設定された幅と精度の指定子を使用します。これは短すぎる文字列を埋め込み、長すぎる文字列を切り捨てます。 ' - 'フラグは列の値を左揃えにします。

System.out.printf("%-30.30s %-30.30s%n", v1, v2); 
+3

[docs](http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax)のJava文字列フォーマットの詳細 – Rodrigue

+0

'% -30.30s'と '%-30s'? –

+1

@ JohnRPerry .30を使用すると、最大フィールド幅は30になります。長い値は切り捨てられます。 – erickson

22

私はFormatterクラスを使用せずにそれをやった:


System.out.printf("%-10s %-10s %-10s\n", "osne", "two", "thredsfe"); 
System.out.printf("%-10s %-10s %-10s\n", "one", "tdsfwo", "thsdfree"); 
System.out.printf("%-10s %-10s %-10s\n", "onsdfe", "twdfo", "three"); 
System.out.printf("%-10s %-10s %-10s\n", "odsfne", "twsdfo", "thdfree"); 
System.out.printf("%-10s %-10s %-10s\n", "osdne", "twdfo", "three"); 
System.out.printf("%-10s %-10s %-10s\n", "odsfne", "tdfwo", "three"); 

と出力が

osne  two  thredsfe 
one  tdsfwo  thsdfree 
onsdfe  twdfo  three  
odsfne  twsdfo  thdfree 
osdne  twdfo  three  
odsfne  tdfwo  three 
10

後期の答えだったが、あなたは何かについてどのように、幅をハードコーディングしたくない場合これは次のように機能します:

public static void main(String[] args) { 
    new Columns() 
     .addLine("One", "Two", "Three", "Four") 
     .addLine("1", "2", "3", "4") 
     .print() 
    ; 
} 

そしてディスプレイ:まあ

One Two Three Four 
1 2 3  4  

それが取るすべては次のとおりです。

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 

public class Columns { 

    List<List<String>> lines = new ArrayList<>(); 
    List<Integer> maxLengths = new ArrayList<>(); 
    int numColumns = -1; 

    public Columns addLine(String... line) { 

     if (numColumns == -1){ 
      numColumns = line.length; 
      for(int column = 0; column < numColumns; column++) { 
       maxLengths.add(0); 
      } 
     } 

     if (numColumns != line.length) { 
      throw new IllegalArgumentException(); 
     } 

     for(int column = 0; column < numColumns; column++) { 
      int length = 
       Math.max( 
        maxLengths.get(column), 
        line[column].length() 
       ) 
      ; 
      maxLengths.set(column, length); 
     } 

     lines.add(Arrays.asList(line)); 

     return this; 
    } 

    public void print(){ 
     System.out.println(toString()); 
    } 

    public String toString(){ 
     String result = ""; 
     for(List<String> line : lines) { 
      for(int i = 0; i < numColumns; i++) { 
       result += pad(line.get(i), maxLengths.get(i) + 1);     
      } 
      result += System.lineSeparator(); 
     } 
     return result; 
    } 

    private String pad(String word, int newLength){ 
     while (word.length() < newLength) { 
      word += " ";    
     }  
     return word; 
    } 
} 

、それはすべての行を持ってまで、それは印刷されませんので、それが列を作る方法を広い学ぶことができます。幅をハードコードする必要はありません。

+0

私はJavaでちょっと新しく、あなたのメソッドが互いにどのように通信するのか混乱しています。 'maxLengths.set(i、Math.max(maxLengths.get(i)、line [i] .length())'これは正確に何をしますか?ご質問のおかげで申し訳ありません。私はちょうどそれがどのように正確に動作するのかわからないコードを使用するのが好きではありません。 – Wax

+0

@Wax ok。 – CandiedOrange

関連する問題