Variables and While Loops

Why can’t I use a variable inside a while loop that I declared outside said while loop? Or do I need to create a global variable, in which case, how do I do that?
Code:
Outside the while loop:
while (!letter.equals(“X”)&&!letter.equals(“O”)){
System.out.println(“Which letter do you want? (X/O): “);
letter = scan.nextLine().toUpperCase();
}
if (letter.equals(“O”)){
String comp = “X”;
}
else if (letter.equals(“X”)){
String comp = “O”;
}
Inside the while loop:
Boolean check2 = false;
while(check2 == false){
comp_x = ThreadLocalRandom.current().nextInt(0,2);
comp_y = ThreadLocalRandom.current().nextInt(0,2);
if(grid[comp_x][comp_y].equals(”-”)){
check2 = true;
}
}
grid[comp_x][comp_y] = comp;
As can be seen, I do create the “comp” variable outside the loop, but it doesn’t recognise the variable inside the loop…

Variables made inside a loop are only available in that loop, the block scope. So just initialize the variable before entering the loop.

String comp = "";
if (letter.equals("O")){
    comp = "X";
}
else if (letter.equals("X")){
    comp = "O";
}
int comp_x = 0;
int comp_y = 0;
Boolean check2 = false;
while(check2 == false){
    comp_x = ThreadLocalRandom.current().nextInt(0,2);
    comp_y = ThreadLocalRandom.current().nextInt(0,2);
    if(grid[comp_x][comp_y].equals("-")){
        check2 = true;
    }
}
1 Like