简体   繁体   中英

Convert int[][] to String

I have a 2d array and i want to convert it to String example

I want to convert int[][] p to String and I use toString but it fail.

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

Your code doesn't compile because:

  1. You're trying to invoke a method on a primitive;
  2. You're missing parentheses on that method call.

This:

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

should be

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

Or, easier:

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

If you're going to build strings in loops, you should avoid concatenation, and use a StringBuilder instead:

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

Of course, the easier way in general to convert a 2D array to a string is using:

String str = Arrays.deepToString(p);

But this might not be in the format you desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM