user1157684
user1157684

Reputation: 1

2-D Array Method Construction

I am having some difficulty filling a 2-D array. Beforehand, I constructed a 2-D array with dimensions based upon user input. Basically I need to check if this statement is valid (still within the array dimensions). Does anyone know how I can do this?

(square[0 - i][dimension/2 + i]) // is valid / still in array dimensions

Thanks

Upvotes: 0

Views: 93

Answers (2)

Radu Murzea
Radu Murzea

Reputation: 10900

Another thing you could do is enclose the "suspect" statement(s) in a try-catch block, with the catch block catching an ArrayIndexOutOfBoundsException and taking the appropiate measures for it (printing an error on the screen, for example).

Like this:

Scanner in = new Scanner(System.in);

int i, j;

i = in.nextInt ();
j = in.nextInt ();

in.close ();

try
{
    System.out.println (the_array[i][j]); //anything else can go here (maybe add that array element to another array ?)
}
catch (ArrayIndexOutOfBoundsException e)
{
    System.err.println ("invalid input"); //anything else can go here (maybe ask for another input ?)
}

Upvotes: 0

Nyubis
Nyubis

Reputation: 558

If you mean you want to check whether the dimensions the user entered aren't too small for you to do your thing, you'll want to use square.length and square[0].length (for the subarray). Example:

int array[5][6] = new int;

System.out.println(array.length);
System.out.println(array[0].length);

This would return:

5
6

So you can just use .length to check whether the values are in the range you need.

Upvotes: 1

Related Questions