如何从字符串数组构建2D int数组?

时间:2015-02-04 19:10:19

标签: java arrays

我正在尝试从字符串数组构建一个2d int数组。我从输入文件中解析了字符串,以便每个字符串都包含int数组行的数字。我不确定我做错了什么。有任何想法吗? 相关代码:

String arrayA[] = ["", 
                  "1 2 -2 0 ",
                  "-3 4 7 2 ",
                  "6 0 3 1 "]
String aryA[] = new String[arrayA.length];
int rowsA[] = new int[3];
int colsA[] = new int[4];
int a[][] = new int[rowsA.length][colsA.length];
String row1A[];
for(int i = 0, j = 1; i < rowsA.length; j++, i++){
    row1A = arrayA[j].split(" ");
    System.out.println(row1A[j]);
    try {
        rowsA[i] = Integer.parseInt(row1A[i]);
    }
    catch (NumberFormatException e) {
        System.out.println("Input was not an int");
    }
}

3 个答案:

答案 0 :(得分:1)

数组使用大括号而不是方括号

String[] arrayA = { "", "1 2 -2 0 ", "-3 4 7 2 ", "6 0 3 1 " };

答案 1 :(得分:0)

以下代码段填充由变量a定义的内容为arrayA的二维数组:

    String arrayA[] = {"", 
                       "1 2 -2 0 ",
                       "-3 4 7 2 ",
                       "6 0 3 1 "};

     int a[][] = new int[3][4];

     for(int i = 0, j = 1; i < arrayA.length-1; j++, i++){
        String[] row1A = arrayA[j].split(" ");  
        for(int k=0; k<row1A.length; k++) {
           System.out.println(row1A[k]);
           try {
                a[i][k] = Integer.parseInt(row1A[k]);
            }
            catch (NumberFormatException e) {
                System.out.println("Input was not an int");
            }
        }

     }

答案 2 :(得分:0)

为什么不将文件中的数据导入InputStream并改为使用ArrayLists的ArrayList?

例如:

 public void makeAr(){
     public ArrayList<ArrayList<Integer>> my2D = new ArrayList<ArrayList<Integer>>();
     File inputFile = new File("src/main/resources/sample.txt");
     InputStream is = new FileInputStream(inputFile);
     BufferedReader r = new BufferedReader(new InputStreamReader(is));
     try {
         while (r.readLine() != null) {
             String row = r.readLine();
             ArrayList<Integer> ints = new ArrayList<Integer>();
             String row1A[] = row.split(" ");
             for(int q=0;q<row1A.length;q++){
                 ints.add(Integer.parseInt(row1A[q]));
             }
             my2D.add(ints);
         }  
     } catch (IOException e) {e.printStackTrace();}

 }