Klippspringer
Klippspringer

Reputation: 99

How can I convert a 2d Number array into a 2d String array?

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

Answers (2)

Alexandra Dudkina
Alexandra Dudkina

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

WatermelonOof
WatermelonOof

Reputation: 21

You can simply use String array instead of Number array. When setting the element, use String.valueOf(YOUR_NUMBER)

Upvotes: 2

Related Questions