Reputation: 99
I'm really new to java or programming, so i have a "basic" quesion (I guess). I have this code, which generates me an array of numbers. I want to convert that into an array of strings. Can someone please fix my code?
public class HelloWorld{
public static void main(String[] args) {
Number[][] values = new Number[10][12];
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values[i].length; j++) {
values[i][j] = Math.floor(Math.random() * 100000) / 100000;
System.out.print(values[i][j] + " ; ");
}
System.out.println();
}
}
}
Upvotes: 0
Views: 49
Reputation: 4462
The most obvious way:
public static String[][] convert(Number[][] numbers) {
String[][] result = new String[numbers.length][];
for (int i = 0; i < numbers.length; i ++) {
Number[] row = numbers[i];
result[i] = new String[row.length];
for(int j = 0; j < row.length; j ++) {
result[i][j] = row[j] == null ? null : row[j].toString();
}
}
return result;
}
Less obvious way:
public static String[][] convert(Number[][] numbers) {
return Arrays.stream(numbers)
.map(row -> Arrays.stream(row).map(n -> String.valueOf(n)).toArray(String[]::new))
.toArray(String[][]::new);
}
Upvotes: 1
Reputation: 21
You can simply use String array instead of Number array. When setting the element, use String.valueOf(YOUR_NUMBER)
Upvotes: 2