我想转换字符串数组,例如
str1[][] ={{"1,2,3,4","0","2,1"}};
到这样的int数组:
int arr[][]={{1,2,3,4},{0,0,0,0},{2,1,0,0}}
我不能只使用split方法,因为每次迭代后tempString的大小都会改变。
我的代码:
int numOfelements = 3;
String str1[][] = { { "1,2,3,4", "0", "2,1" } };
int graph[][] = new int[numOfelements][numOfelements];
String str[]= new String[numOfelements];
for (int i = 0; i < numOfelements; ++i) {
str = str1[i][0].split(",");
for (int j = 0; j < numOfelements; ++j) {
try {
if (str.length < j)
graph[i][j] = Integer.parseInt(str[i]);
else
graph[i][j] = 0;
} catch (Exception e) {
JOptionPane.showMessageDialog(new JFrame(), "Error in the data!",
"Error", JOptionPane.ERROR_MESSAGE);
break;
}
}
}
答案 0 :(得分:1)
您可以编写一个自定义方法来用零填充数组。如果您谨慎使用,.split()
仍然可以使用。
public static int[] fillArray(String s, int size){
String[] tok = str.split(",");
int[] newArr = new int[size];
for(int x=0; x<Math.min(size, tok.length); x++)
newArr[x] = Integer.parseInt(tok[x]);
for(int x=Math.min(size, tok.length); x<Math.max(size, tok.length); x++)
newArr[x] = 0;
return newArr;
}
获取数组数据并用零填充并将其放回新数组中:
int[][] arr;
for(int x=0; x<str1[0].length; x++)
arr[0][x] = fillArray(str1[0][x], 4); //size of 4 can be changed to your needs
答案 1 :(得分:0)
试试这个解决方案:
int numOfelements = 4;
String str1[][] = { { "1,2,3,4", "0", "2,1" }};
int graph[][] = new int[numOfelements][numOfelements];
String str[]= new String[numOfelements];
for (int k = 0; k < str1.length; k++) {
int len =str1[k].length;
for (int i = 0; i < len; i++) {
str = str1[k][i].split(",");
for(int j = 0; j < str.length; j++ )
graph[i][j]=Integer.parseInt(str[j]);
}
}