2017-03-27 4 views
0

so versuche ich meine Ausgabejava Formatierung tabellarische Ausgabe

System.out.println("Menu:\nItem#\tItem\t\tPrice\tQuantity"); 
    for(int i=0;i<stock.length;i++){ 
     System.out.println((i+1)+"\t"+stock[i].Description + "\t\t"+stock[i].price + "\t"+stock[i].quantity); 

the output should be like

but it comes out as

+0

Ich würde empfehlen, – MadProgrammer

+1

einige der Forschung in printf und String # Format tun Sie nicht korrekt zu formatieren Dinge auf Registerkarten zählen. Je. Benutze sie einfach nicht. – ajb

Antwort

1

Java-Format hat eine schöne glückliche Weise Tabellen auszudrucken mit System.out.format

Hier ein Beispiel:

Object[][] table = new String[4][]; 
table[0] = new String[] { "Pie", "2.2", "12" }; 
table[1] = new String[] { "Cracker", "4", "15" }; 
table[2] = new String[] { "Pop tarts", "1", "4" }; 
table[3] = new String[] { "Sun Chips", "5", "2" }; 

System.out.format("%-15s%-15s%-15s%-15s\n", "Item#", "Item", "Price", "Quantity"); 
for (int i = 0; i < table.length; i++) { 
    Object[] row = table[i]; 
    System.out.format("%-15d%-15s%-15s%-15s\n", i, row[0], row[1], row[2]); 
} 

Ergebnisse:

Item#   Item   Price   Quantity  
0    Pie   2.2   12    
1    Cracker  4    15    
2    Pop tarts  1    4    
3    Sun Chips  5    2    
+0

wow danke mann, ich versuche es auch mit dem printf zu machen – irrelevent

+1

'System.out.prinf' &' System.out.format' sind eigentlich das gleiche! Wie in [diese Frage] (http://stackoverflow.com/questions/16234448/system-out-printf-vs-system-out-format) gezeigt. –

+0

Oh gut, ich habe endlich dieses 'System.out.printf (" Menü: \ n% -10s% -10s% 12s% 14s \ n "," Artikel # "," Artikel "," Preis "," Menge ") ; \t \t for (int i = 0; i irrelevent