我已經將txt文件轉換爲2d數組,我怎樣才能讓它看起來更加整齊?將2d數組轉換爲組織表外觀
我的輸入文件是這樣的:
[Name], Exam1, Exam2, Exam3 John, 99, 88, 89 May, 99, 100, 100 Mary, 100, 100, 100 Peter, 60, 60, 60
目前我得到:
[Name] Exam1 Exam2 Exam3 John 99 88 89 May 99 100 100 Mary 100 100 100 Peter 60 60 60
我想要的數據看起來更像是一個表,它是更容易閱讀,我該怎麼辦呢?
代碼:
public static void main(String[] args) throws Exception{
File file = new File("test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
int width = 0, height = 0;
String line = "";
/*Find number of row and column of the file.*/
while ((line = br.readLine()) != null)
{
if (width == 0)
{
/*Find the number of row using split method(",")*/
String[] str = line.split(",");
width = str.length;
}
height++;
}
System.out.println("Row : " + height);
System.out.println("Column : " + width);
/*Adding values to the 2D Array.*/
String[][] data = new String[height][width];
br = new BufferedReader(new FileReader(file));
for (int i = 0; i < height; i++)
{
if ((line = br.readLine()) != null)
{
for (int j = 0; j < width; j++)
{
String[] str = line.split(",");
data[i][j] = str[j];
System.out.print(data[i][j] + " ");
}
}
System.out.println("");
}
}
非常感謝你。用printf
,或者您可以使用格式化
謝謝回答。我是新來的java,在哪裏以及如何使用printf/Formatter?非常感謝。 – 2012-01-12 17:27:03
沒有問題 這裏是一個鏈接到api格式化程序:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html 至於printf,我不認爲api談論太多的用法。這裏是一個例子:http://www.java2s.com/Code/JavaAPI/java.lang/SystemoutprintfsssnStringstr1Stringstr2Stringstr3.htm 如果你是java新手,你最好的朋友是api文檔和源代碼。 :) – ligerdave 2012-01-12 18:48:51