2009-03-31 10 views

Respuesta

48

Utilice los especificadores de ancho y precisión, establecidos en el mismo valor. Esto rellenará cadenas que son demasiado cortas y truncar cadenas que son demasiado largas. El indicador '-' justificará a la izquierda los valores en las columnas.

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

Más detalles sobre el formato de cadenas de Java en [los documentos] (http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax) – Rodrigue

+0

¿Cuál es la diferencia entre '% -30.30s' y '% -30s'? –

+1

@JohnRPerry Con .30, el ancho máximo del campo es 30. Los valores más largos se truncarán. – erickson

22

lo hice sin utilizar clase de formateador como:


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"); 

y la salida estaba

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

respuesta tardía pero si usted no desea codificar el ancho, la forma de algo que funciona así:

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

y muestra:

One Two Three Four 
1 2 3  4  

Bueno, todo lo que necesita es:

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

Dado que no se imprimirá hasta que tenga todas las líneas, se puede aprender de ancho para hacer las columnas. No hay necesidad de codificar el ancho.

+0

Soy un poco nuevo en Java, y estoy confundido sobre cómo sus métodos se comunican entre sí. 'pad()' y 'System.lineSeparator()' y esta línea 'maxLengths.set (i, Math.max (maxLengths.get (i), línea [i] .length())' ¿qué hace exactamente esto? Lo siento por el aluvión de preguntas. Simplemente no me gusta usar el código que no sé cómo funciona exactamente. – Wax

+0

@Wax está bien. ¿Mejor? – CandiedOrange

Cuestiones relacionadas