2

I created a method that reads a bunch of numbers from a file, takes the first two numbers to be the row and the column length of the array, then converts the rest of them into integers and places the integers into the two dimensional array:

public static int[][] fillArray(String myFile){
    //uses another class to create a text field
    TextFileInput in = new TextFileInput(myFile); 

    int[][] filledArray;
    //uses a method in class TextInputFile to read a line then go to the next line
    String line = in.readLine();
    //int i=0;
    int row, col;
    row = Integer.parseInt(line);
    line = in.readLine();
    col = Integer.parseInt(line);
    filledArray = new int[row][col];
    for(int i=0; i<row; i++){
        for (int j=0; j<col; j++){
            line = in.readLine();
            filledArray[i][j] = Integer.parseInt(line);
        }
    }
    return filledArray;
}

My question is how would I access the individual elements in my multidementional array filledArray? As in, how would I print what's in filledArray[1][3] or add filledArray[1][3]+filledArray[2][3] in the main method?

4

3 回答 3

2

fillArray 方法返回对其创建的数组的引用。您所要做的就是在您的 main 方法中为此分配一个局部变量。

public static void main(String[] args) {
   int[][] arr = fillArray("file.txt");

   System.out.println(arr[1][3]);

   System.out.println(arr[1][3] + arr[2][3]);
}

您可以通过使用数组中的索引来访问各个元素,例如arr[4][2]. 请注意不要生成IndexOutOfBoundsException,这就是为什么在 for 循环中检查数组长度是个好主意的原因。

于 2013-03-09T15:31:40.443 回答
2

只需将返回的数组存储在本地数组中

public static void main(String[]args){
  int[][]array = fillArray("fileName"); // call the method
  // traverse the array using a loop

  for(int i=0;i<array.length;i++)
    for(int j=0;j<array[i].length;j++)
     System.out.println(a[i][j]); // do something with elements 

 }
于 2013-03-09T15:31:42.977 回答
1

您将获取 的结果fillArray(...),将其存储在变量中,然后对其进行处理。

例如

int[][] filled=fillArray("file.txt");
System.out.println(filled[1][3]);
System.out.println(filled[1][3]+filled[2][3]);
于 2013-03-09T15:32:08.870 回答