'My code is giving me some weird message, but I don't know how to interpret it
When I try and compile this code, Eclipse gives these two errors:
for the
maxminfunction: illegal modifier for maxmin; only final is permittedfor
Mn: Mn cannot be resolved to a variable
Why do these two errors appear?
I think this might have answered it, but I can't understand the jargon used in it.
Here's my code:
public static int maxmin(int [][]B, int ver) {
if (ver == 1) { // Maximum operation
int M = 0;
for (int m = 1; m < 3; m++) {
for (int n = 1;n < 3; n++) {
if (M < B[m][n]) {
M = B[m][n];
}
}
}
return M;
} else if (ver == 2) { // Minimum operation
int Mn = 10;
}
for (int m = 1; m < 3; m++) {
for (int n = 1; n < 3; n++) {
if (Mn > B[m][n]) {
Mn = B[m][n];
}
}
}
}
return Mn;
}
Solution 1:[1]
The Mn variable is defined inside the else if block. Hence when you are accessing it inside the for loop, it does not find its declaration. Insetad you should move the declaration int Mn = 0 at the beginning the method and assign it to 10 inside the else if
Solution 2:[2]
public static int maxmin(int[][] B, int ver) {
if (ver == 1) {// max operation
int M = 0;
for (int m = 1; m < 3; m++) {
for (int n = 1; n < 3; n++) {
if (M < B[m][n]) {
M = B[m][n];
}
}
}
return M;
} else if (ver == 2) {// min operation
int Mn = 10;
for (int m = 1; m < 3; m++) {
for (int n = 1; n < 3; n++) {
if (Mn > B[m][n]) {
Mn = B[m][n];
}
}
}
return Mn;
} else {
throw new IllegalArgumentException("invalid ver, must be 1 or 2");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ashish |
| Solution 2 | salyh |
