英文:
How can I convert a 2d Number array into a 2d String array?
问题
public class HelloWorld {
public static void main(String[] args) {
String[][] strings = new String[10][12];
for (int i = 0; i < strings.length; i++) {
for (int j = 0; j < strings[i].length; j++) {
strings[i][j] = String.valueOf(Math.floor(Math.random() * 100000) / 100000);
System.out.print(strings[i][j] + " ; ");
}
System.out.println();
}
}
}
英文:
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();
}
}
}
答案1
得分: 2
你可以直接使用字符串数组而不是数字数组。在设置元素时,使用 String.valueOf(YOUR_NUMBER)
。
英文:
You can simply use String array instead of Number array. When setting the element, use String.valueOf(YOUR_NUMBER)
答案2
得分: 1
最明显的方法:
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;
}
不太明显的方法:
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);
}
英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论