Eonm Eonm - 2 months ago 41
Java Question

int[][] cannot be converted to int

System.out.println("Enter number of rows");
int row = sc.nextInt();
int[][] twod = new int[row][];
for (int i=0; i < row; i++)
{
int p = i+1;
System.out.println("Enter number of columns for row number "+p);
int column = sc.nextInt();
twod[row][column] = new int[row][column];
for(int k = 0; k < column;k++)
{
int wat = k+1;
System.out.println("Enter element in row number "+p+" and column number "+ wat );
twod[i][k] = sc.nextInt();
}
}

for(int men = 0; men < twod.length; men++)
{
for (int women = 0; women < twod[men].length; women++)
{
System.out.print(twod[men][women]);
}
}


When i try to run the program, it gives


incompatible types: int[][] cannot be converted to int
twod[row][column] = new int[row][column];


But i've already declared
twod
as an
int[][]
. Then why is the error showing up?

Answer Source

This is a whole code for you.

import java.util.Scanner;

public class TestArray {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter number of rows");
        int row = sc.nextInt();
        int[][] twod = new int[row][];
        for (int i = 0; i < row; i++) {

            int p = i + 1;
            System.out.println("Enter number of columns for row number " + p);

            int column = sc.nextInt();//for simplicity

            twod[i] = new int[column];

            for (int k = 0; k < column; k++) {
                int wat = k + 1;
                System.out.println("Enter element in row number " + p + " and column number " + wat);
                twod[i][k] = sc.nextInt();
            }
        }

        for (int men = 0; men < twod.length; men++) {
            for (int women = 0; women < twod[men].length; women++) {
                System.out.print(twod[men][women]);
            }
        }
    }
}

First, you create empty two dimensional array and each row has a one dimensional array.

int[][] twod = new int[row][];

Then, you must specify each one dimensional array from the user input in a for statement.

twod[i] = new int[column];

The type of int is one of primitive type in java, so you don't need to create memory space with new keyword.

But, you should think if your type of arrays are object in which you must create some memory for the object with new as a java's keyword.

Then, I don't know what you want to do with your last for statement.

Regards,