Log Log - 4 months ago 10
Java Question

Defining array as class variable with user input for dimensions

I wish to declare an array as a class variable but with dimensions input from the user.

class whatever
{
int array[][]=new int [n][n]; //this is a wrong definition

public void method()
{
//method content
}
}


Here n is the required input.

Answer

You can pass n as an argument to the constructor of your class1. Something like

class Whatever {
   int[][] array;
   public Whatever(int n) {
       this.array = new int[n][n];
   }

   public void method()
   {
       //method content
   }
}

1 And, by convention, Java class names should start with a capital letter.