Search code examples
javaminesweeper

2d-array error with the length


I am having some truble in this part of the code cols = input[0].length() ; it says to me that 1) cannot invoke length of the primitive type of int 2)length cannot be resolved or is not field. i am doning a code for minesweeper game and here i want to fill the grid with the index from the file I have.

public static void main(String[] args) {

    Scanner file = new Scanner ("in.txt");

    int line=0;
    int m = file.nextInt();
    int n = file.nextInt();
    int index = file.nextInt();

    int [][] input = new int[m][n];
    String.valueOf(input);

    for (int [] field : input) {
        printMineField(field);
    }
    file.close();
    line= line++;
}

private static void printMineField(int[] input) {


    int rows = input.length, cols = input[0].length ;
    int[][] grid = new int[rows][cols];


    for (int i = 0; i < rows; i++) {
        Arrays.fill(grid[i], 0);
    }
    //
}

Solution

  • First length is a field in array, not a function. So you should use cols = input[0].length; - remove those parenthesis.

    Next, You are passing one dimensional array to your method. You should pass a two dimensional array.

    Replace

    private static void printMineField(int[] input) 
    

    with:

    private static void printMineField(int[][] input) 
    

    Then you will also need to replace

    for (int [] field : input) {
        printMineField(field);
    }
    

    with:

    printMineField(input);