2012-01-12 7 views
0

txt 파일을 2 차원 배열로 변환했는데, 어떻게하면 더 조직적으로 보이게 할 수 있습니까? 이 같은2 차원 어레이를 구성 테이블 모양으로 변환

내 입력 파일보기는 :

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

    } 
} 

가 대단히 감사합니다.

또는

답변

1

시도 출력 :

// To Store and Show Values on the screen. 
    int columnWidth = 15; 

    for (int i = 0; i < height; i++) 
    { 
     if ((line = br.readLine()) != null) 
     { 
      // After reading, we are seperating them. 
      String[] str = line.split(", "); 
      for (int j = 0; j < width; j++) 
      {               
       data[i][j] = str[j]; 
       // Here we are making the word length of each String equal, 
       // i.e. equal to column width. So that each String value comes 
       // below each other. Increase the value of columnWidth variable 
       // if you want to increase the width of a column or vice versa. 
       System.out.format("%-" + columnWidth + "s", data[i][j]); 
      } 
     } 
     System.out.print("\n"); 
    } 

희망 도움이 될 수 있습니다.

감사

+0

감사 (비록 열을 줄을 패딩하지, 그게 당신이 할 수 있도록, 쉽게 신뢰 날입니다). 나는 자바를 처음 사용하는데 printf/Formatter를 어디서 어떻게 사용 하는가? 고마워. –

+0

문제 없음 여기는 api Formatter에 대한 링크입니다. 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 자바를 처음 접한다면 가장 친한 친구는 API 문서와 소스 코드입니다. :) – ligerdave

0

당신은 다음과이 방법에 그것을 할 수 포맷터 사용의 printf를 사용하여

+0

감사합니다. 작동합니다. 하지만 언젠가 그 단어가 너무 길면 언뜻보기에 더 큰 차이가납니다. 어떻게 해결할 수 있습니까? 고마워. –

+0

@BensonLeung : 컬럼 내부의 값을 수용하기 위해 원하는대로 columnWidth의 값을 늘리거나 줄입니다. 열이 넓어 지길 원한다면 늘리십시오. 원한다면 열을 줄이십시오. 감사합니다 –

+0

@BensonLeung : 이제 나는 필요한 변화를 했으니 지금 시도하십시오. 문안 인사 –

0

나는 당신이 당신의 제품에 모든 System.out에 물건을 싶지 않을 그러나 나는 당신에게 당신이해야 할 기본 단계를 보여주기 위해 당신 구축, 예에서 사용하기 위하여려고하고 상상 .

기본적으로 데이터를 두 번 통과해야합니다. 첫 번째 단계에서는 데이터의 가장 넓은 행을 계산해야하므로 ---- 행을 만들 수 있습니다. 그런 다음 원하는 출력 유형 (여기서는 System.out)을 추가 한 다음 데이터를 다시 걷고 출력에 추가합니다. 개행 문자 나 다른 종결자를 추가해야합니다. 열을 정렬하려면 동일한 작업을 수행하지만 첫 번째 단계에서는 다차원 배열에 각 열에 가장 넓은 데이터를 기록하고 출력시 각 열의 너비가 가장 짧은 패드 데이터를 채 웁니다. --- 선의 너비를 변경하십시오. 물론 선을 작성하기 전에 이것을 계산해야합니다.)

가 여기에 귀하의 예는이 아이디어의 일부 약간의 수정 답변에 대한

public static void main(String[] args) throws Exception { 

    /* Adding values to the 2D Array. */ 

    String[][] data = { { "John", "99", "88", "89" }, 
      { "May", "99", "100", "100" } }; 

    int wideRowWidth = 0; 
    int curRowWidth; 

    // WALK DATA ONCE TO FIND THE WIDEST ROW 
    for (int i = 0; i < data.length; i++) { 
     curRowWidth = 0; 
     for (int j = 0; j < data[i].length; j++) { 
      curRowWidth += data[i][j].length(); 
     } 
     if (curRowWidth > wideRowWidth) { 
      wideRowWidth = curRowWidth; 
     } 

    } 

    // BUILD YOUR DASHED LINE 
    for (int i = 0; i < wideRowWidth + data[0].length -1; i++) { 
      System.out.print("-"); 
    } 
    System.out.print("\n"); 

    // USE YOUR DATA 
    for (int i = 0; i < data.length; i++) { 
     for (int j = 0; j < data[i].length; j++) { 
      System.out.print(data[i][j] + " "); 
     } 
     System.out.print("\n"); 
    } 
} 
관련 문제