我想将一维字符串数组转换为二维数组
行数等于数组元素的数量。
一维数组有很多元素,因此每个元素应该位于一行
split 成九个元素后。
但是除了异常之外输出都是一维数组 java.lang.ArrayIndexOutOfBoundsException 9
有人可以帮忙吗?
public class StringFragementation
{
public static String [][] mymethod(String [] mystring)
{
int row = 0, col = 0;
String[][] india = new String[2][9];
String mystringno2[];
mystringno2 = mystring;
int i = 0;
int j = 0;
String x = "_";
int i1;
String Nahda="";
int l;
for( l=0;l<mystringno2.length;l++)
{
Nahda = Nahda.concat(mystringno2[l]);
}
System.out.println( Nahda );
i1 =0;
while (j <Nahda.length())
{
i = Nahda.indexOf(x, i);
i1 = i + 1;
i1 = Nahda.indexOf(x, i1);
if (i1 >Nahda.length())
{
break;
}
i++;
india[row][col] = Nahda.substring(i, i1);
System.out.print("Element " + row + " " + col + " " + india[row][col]+"\t");
col++;
}
return india;
}
public static void main(String[] args)
{
String[] s ={"_Netherlands_Iceland_Norway_Denmark_Usa_Brazil_Argentina_Colombuia_Bolivia","_Belgium_Romania_France_Germany_Switherland_Russia_Sweden_Italy_Austria"};
String [][] singapore = new String[s.length][9];
singapore = mymethod(s);
for(int col=0,k=0;col <9;col++)
for(int row=0;row<s.length;row++)
{
System.out.print( singapore[row][col++]+"\t" ) ;
}
System.out.println("\n");
}
}
最佳答案
问题在于,如果未找到字符串,indexOf()
将返回 -1。现在,由于包含国家/地区名称的字符串末尾没有 "_"
,因此 indexOf
函数将返回 -1。因此,您的循环将不会退出,col
将变为 9,这会导致 IndexOutOfBoundsException
。
我可能是错的,但尝试在最后添加一个“_”
。
此外,您永远不会在循环中增加 row
,这就是返回的数组中只有一维的原因。
编辑
好的,现在我明白了,所以您有 18 个国家/地区,并且希望将它们排列为 2 行 9 列。好吧,你永远不会增加 row
这样就行不通。
试试这个:
public class StringFragementation
{
public static String [][] mymethod(String [] mystring)
{
int row = 0, col = 0;
String[][] india = new String[2][9];
String mystringno2[];
mystringno2 = mystring;
int i = 0;
int j = 0;
String x = "_";
int i1;
String Nahda="";
int l;
for( l=0;l<mystringno2.length;l++)
{
Nahda = Nahda.concat(mystringno2[l]);
}
System.out.println( Nahda );
i1 =0;
// set i before the loop
i = Nahda.indexOf(x, i);
while (j <Nahda.length()) {
i1 = Nahda.indexOf(x, i + 1);
if (i1 == -1) {
// No more "_" we're at the end but we still need to add the last country!
india[row][col] = Nahda.substring(i, Nahda.length() - 1);
break;
}
india[row][col] = Nahda.substring(i + 1, i1);
// set i to the "_" after the current country.
i = i1;
System.out.print("Element " + row + " " + col + " " + india[row][col].toString()+"\n");
col++;
if (col >= 9) {
// we're at the end of the first row, go to second row
col = 0;
row++;
}
}
return india;
}
public static void main(String[] args)
{
String[] s ={"_Netherlands_Iceland_Norway_Denmark_Usa_Brazil_Argentina_Colombuia_Bolivia","_Belgium_Romania_France_Germany_Switherland_Russia_Sweden_Italy_Austria"};
String [][] singapore = new String[s.length][9];
singapore = mymethod(s);
for(int col=0; col < 9;col++)
for(int row=0;row<s.length;row++)
{
System.out.print( singapore[row][col]+"\t" ) ;
}
System.out.println("\n");
}
}
关于java - 将一维字符串数组转换为二维数组行中的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20192961/