Reputation: 195
I am trying to create a method that creates 2D array of unknown size and uses a loop to fill it with a character provided by the user in the main program. If the user gives e.g. negative values, the method should return null. I can get it to work, when the user uses suitable values, but not when the values are negative.
I use this:
public static char[][] createArr(int row, int col, char ch) {
char array[][] = new char[row][col];
if (row > 0 && col > 0) {
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
array[j][i] = ch;
}
}
}
else {
array = null;
}
return array;
I understand why it doesn't work, because
if (row > 0 && col > 0) {
comes AFTER I create the array, so the negative values create an error. But if I move it, then it gives the "cannot find symbol" error when I try to return the array to the main program.
How can I change this code so that it would not crash when the user inputs negative values?
PS. I am a student and we cannot use all java libraries, so I am asking how to get this type of code working without different helper classes.
Upvotes: 0
Views: 37
Reputation: 2303
public static char[][] createArr(int row, int col, char ch) {
char array[][] = null;
if (row > 0 && col > 0) {
array = new char[row][col];
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
array[j][i] = ch;
}
}
}
return array;
}
Upvotes: 1