I have a for loop, and I initialise the variables inside that loop. After it, I need to manipulate that variables, but the compiler says that variables are not initialised.
public class Solution {
static void displayPathtoPrincess(int n, String[] grid) {
String[][] visual = new String[n][n];
for (int i = 0; i < n; i++) {
char[] myGrid = grid[i].toCharArray();
for (int j = 0; j < n; j++) {
visual[i][j] = myGrid[j] + "";
}
}
int pX;
int pY;
int bX;
int bY;
// rescue the princess
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (visual[i][j].equals("p")) {
pX = j;
pY = i;
}
if (visual[i][j].equals("m")) {
bX = j;
bY = i;
}
}
}
System.out.println(pY + "");
System.out.println(pX + "");
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m;
m = in.nextInt();
String grid[] = new String[m];
for (int i = 0; i < m; i++) {
grid[i] = in.next();
}
displayPathtoPrincess(m, grid);
}
}
if condition is true at some point. In fact if I move the print statements inside the if it works.
How can solve this problem?
ifstatement condition is true at some point in your loop? If it isn't,pXandpYwon't get values.