以下代码应该采用一个元素的String数组,将其拆分为
九个元素应该存储到另外两个维度的数组中。
它们的每个元素都应该单独存储在一列中。
但是当我打印二维数组的元素时,只会打印最后一个元素 为什么呢?
public class StringFragementation {
public static String[][] mymethod(String[] mystring) {
String[][] india = new String[1][9];
String mystringno2[];
mystringno2 = mystring;
int i = 0;
int j = 0;
String x = "_";
int i1;
do {
i = mystringno2[j].indexOf(x, i);
i1 = i + 1;
i1 = mystringno2[j].indexOf(x, i1);
if (i1 <= -1) {
break;
}
i++;
int row, col = 0;
for (row = 0; row < 1; row++) {
for (col = 0; col < 9; col++) {
india[row][col] = mystringno2[j].substring(i, i1);
}
}
}
while (j < mystringno2.length);
return india;
}
public static void main(String[] args) {
String[][] singapore = new String[1][9];
String[] s = {"_Netherlands_Iceland_Norway_Denmark_Usa_Brazil_Argentina_Colombuia_Bolivia_"};
singapore = mymethod(s);
for (int row = 0; row < 1; row++)
for (int col = 0; col < 9; col++) {
System.out.print(singapore[0][0] + "\t");
}
}
}
答案 0 :(得分:2)
问题在于:
for( row=0;row<1;row++){
for( col=0;col< 9;col++) {
india[row][col] = mystringno2[j].substring(i, i1);
}
}
你用相同的单词填充9列,因为i
和i1
永远不会通过此循环更改,然后重新启动数组并填充Netherlands
然后填充Iceland_Norway_Denmark
直到最后一个字
Bolivia
,因此您的数组在9列中填充Bolivia
正确的方法是:
int row = 0, col = 0;
String[][] india = new String[1][9];
String mystringno2[];
mystringno2 = mystring;
int i = 0;
int j = 0;
String x = "_";
int i1;
do {
i = mystringno2[j].indexOf(x, i);
i1 = i + 1;
i1 = mystringno2[j].indexOf(x, i1);
if (i1 <= -1) {
break;
}
i++;
india[0][col] = mystringno2[j].substring(i, i1);
System.out.println("dfref " + row + " " + col + " " + india[row][col]);
col++;
} while (j < mystringno2.length);
return india;
和main
:
for (int row = 0; row < 1; row++) {
for (int col = 0; col < 9; col++) {
System.out.print(singapore[row][col] + "\t");
}
}
有一种最小的方法可以进行这种分割,请看这段代码:
class StringFragementation {
public static String[] mymethod(String mystring) {
String[] split = mystring.split("_");
return split;
}
public static void main(String[] args) {
String[] singapore = new String[9];
String s = "Netherlands_Iceland_Norway_Denmark_Usa_Brazil_Argentina_Colombuia_Bolivia_";
singapore = mymethod(s);
for (int col = 0; col < 9; col++) {
System.out.println(singapore[col]);
}
}
}