I want to make a variable that I can use inside my method to change that variable outside my method. As a visual: (I imported the scanner class by the way)
public static void main(String[] args) {
int quitVar = 1;
Scanner scan = new Scanner(System.in);
class IWantToQuit {
public void quit() {
quitVar++; //This is the problem area.
}
}
IWantToQuit quiter = new IWantToQuit();
while (quitVar == 1) {
System.out.println("HELLO");
System.out.println("Type QUIT to quit.");
choice = scan.next();
if (choice.equals("QUIT")) {
quiter.quit();
}
For some reason, it says that the local variable quitVar is accessed by the inner class but it needs to be declared and I have declared it. Any help is appreciated.
This local inner class because defined inside method. Rules for local inner class are:
A local class has access to the members of its enclosing class.
In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final.
In this case quitVar
is local variable, so you need to declare it as final
to access it inside local class. But if you declare it final
, you can't increment.
If you want this variable accessible, then define as class variable rather than local variable.