views:

48

answers:

4

How can i convert the ints in a 2d array into chars, and strings? (seperately)

If i copy ints to a char array i just get the ascii code.

For example

public int a[5][5]

//some code

public String b[5][5] = public int a[5][5]

Thanks

A: 

Your code must basically go through your array and transform each int value into a String. You can do this with the String.toString(int) method.

You can try that :

String[][] stringArray = new String[a.length][];
for(int i = 0; i < a.length; i++){
    stringArray[i] = new String[a[i].lenght];
    for(int j = 0; j < a[i].length; j++){
        stringArray[i][j] = Integer.toString(a[i][j]);
    }
}
Colin Hebert
A: 

If you want the int number as a string then you can use the Integer.toString() function.

b[1][1] = Integer.toString(a[1][1]);
kyndigs
A: 
String [][]b = new String[a.length][];
for(int i=0; i<a.length; i++) {
  int [] row = a[i];
  b[i] = new String[row.length];
  for(int j=0; j<row.length; j++) {
    b[i][j] = Integer.toString(row[j]);
  }
}
Nick Fortescue
+1  A: 

This question is not very well-phrased at all. I THINK what you're asking is how to convert a two-level array of type int[][] to one of type String[][].

Quite frankly, the easiest approach would simply leave your array as-is... and convert int values to String's when you use them:

Integer.toString(a[5][5]);

Alternatively, you could start with a String[][] array in the first place, and simply convert your int values to String when adding them:

a[5][5] = new String(myInt);

If you really do need to convert an array of type int[][] to one of type String[][], you would have to do so manually with a two-layer for() loop:

String[][] converted = new String[a.length][];
for(int index = 0; index < a.length; index++) {
    converted[index] = new String[a[index].length];
    for(int subIndex = 0; subIndex < a[index].length; subIndex++){
        converted[index][subIndex] = Integer.toString(a[index][subIndex]);
    }
}

All three of these approaches would work equally well for conversion to type char rather than String.

Steve Perkins