2D字符串数组到2D Int数组

时间:2018-04-09 19:16:00

标签: java arrays string integer

我想将2D字符串数组转换为整数2D数组。怎么做。我尝试了一些东西,但我现在无法集中注意力,并希望今天完成它:D提前谢谢。 所以...这里是数组的所有值:

parts[] []: 

[0] "25"
[1] "3"
[2] "18"

[0] "20"
[1] "12"
[2] "18"

[0] "1"
[1] "1"
[2] "15"

//string.length = 3;

String[] [] parts = new String[string.length][];
int[] [] stringToInt = new int[string.length][];

for(int a=0; a<string.length;a++){
    for(int b=0; b<3;b++){
      stringToInt[a] = Integer.parseInt(parts[a] [b]);    <---Error
    }
}

2 个答案:

答案 0 :(得分:2)

初始化字符串数组,然后定义2D int数组时遇到一些问题。这可能是你的意思:

String parts[][] = { { "25", "3", "18" }, { "20", "12", "18" }, { "1", "1", "15" } };

int[][] stringToInt = new int[parts.length][parts[0].length];

for (int a = 0; a < parts.length; a++) {
    for (int b = 0; b < parts[0].length; b++) {
        stringToInt[a][b] = Integer.parseInt(parts[a][b]);
    }
}

答案 1 :(得分:0)

    public static void main(String[] args) {
    int cols = 3;
    int rows = 3;
    String [][] parts = new String[cols][rows];

    //init the 2d array
    parts[0][0] = "25";
    parts[0][1] = "3";
    parts[0][2] = "18";

    parts[1][0] = "20";
    parts[1][1] = "12";
    parts[1][2] = "18";

    parts[2][0] = "1";
    parts[2][1] = "1";
    parts[2][2] = "15";

    //the array you want
    int [][] intArray = new int [cols][rows];

    for(int c = 0; c < cols; c++){

        for(int r = 0; r < rows; r++){
            intArray[c][r] = Integer.parseInt(parts[c][r]);
        }

    }


}

我认为您的错误可能是因为您提供了stringToInt[a]=而不是stringToInt[a][b]=