2017-04-21 204 views
0

我有一個二維數組,我想將其轉換爲字符串示例轉換INT [] []將字符串

int[][] p轉換爲String我用toString但它會失敗。

int [][] p = new int[9][9]; 
for(int i = 0;i<9;i++) { 
    for(int j = 0;j<9;j++){ 
     p[i][j] = 1; 
    } 
} 

String str=""; 
for(int i = 0; i< 9; i++) { 
    for(int j = 0; j< 9; j++) 
    { 
     str+=p[i][j].toString +" "; 
    } 
} 
+3

'Arrays.deepToString(p);' –

+3

'Arrays.deepToString(p)'。 –

+2

@ElliottFrisch jinx。幾乎完全在同一時刻。 –

回答

8

您的代碼不編譯,因爲:

  1. 你試圖調用一個原始的方法;
  2. 你缺少該方法調用的括號。

此:

str+=p[i][j].toString +" "; 

應該

str+=Integer.toString(p[i][j]) +" "; 

或者,更容易:

str+=p[i][j] +" "; 

如果你要建立循環字符串,你應該避免級聯,並使用StringBuilder代替:

StringBuilder sb = new StringBuilder(); 
for(int i = 0; i< 9; i++) { 
    for(int j = 0; j< 9; j++) 
    { 
     sb.append(p[i][j]); 
     sb.append(" "); 
    } 
    // You maybe want sb.append("\n") here, if you want it on separate lines. 
}  
String str = sb.toString(); 

當然,在一般的更簡單的方法來轉換一個二維數組到一個字符串使用:

String str = Arrays.deepToString(p); 

但是,這可能不是你想要的格式。

+0

太棒了。有一個upvote。 – Bathsheba

+0

@Bathsheba但後來太短了。我試過了。 –

+0

我管理。也許那是因爲我很有錢。 – Bathsheba