我有以下字符串代码
[444398, 1]
[111099, 0]
[188386, 2]
[149743, 0]
我想创建一个二维数组,其中每个数字都是一个 int。 例如,
int[][] temp = new int[4][2]
我正在尝试使用
String challengetemp = Arrays.toString(Challenge.challenge(players[0], players[1]));
challengeList[i][i] = Integer.parseInt(challengetemp.split("\\|",-1));
但对于初学者来说,ParseInt 会出现类型不匹配并导致错误。
我需要能够随后以整数形式访问数组中的信息
最佳答案
我会利用StringTokenizer做这样的事情。
String str = "[444398, 1][111099, 0][188386, 2][149743, 0]";
str = str.replace("[","");
str = str.replace("]","|");
int arr[][] = new int[4][2];
StringTokenizer token = new StringTokenizer(str,"|");
for(int i=0;i<4;i++)
{
StringTokenizer nextToken = new StringTokenizer(token.nextToken(),",");
for(int j=0;j<2;j++)
{
String tokenValue = nextToken.nextToken();
if(tokenValue.contains("|"))
{
tokenValue.replace("|", "");
}
arr[i][j]= Integer.parseInt(tokenValue.trim());
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
System.out.println(arr[i][j]);
}
};
并且您必须对循环进行一些修改,以便它可以根据需要将尽可能多的 String 解析为 int 数组。
关于java - 字符串转int数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17621568/