简体   繁体   中英

local variable cannot be assigned as final

I have a variable that asks me to make it final, but when making it final I get an error that says the following: "The final local variable "enter" cannot be assigned, since it is defined in an endclosing type"

How could you declare such a variable?

void yyyyyy(ActionEvent event){

final Scanner enter = null;

try{
.
.
.
enter = new Scaner(xxxxx);

}catch(){
....
}finally{
  if(enter != null){
}
}

Right now you declare the variable and initialize it in the same time. Since it's final, you can not assign values to it more, than once.

If you remove assignment from initialization, you still can not make this variable final, because you check it for null in finally block. For that logic to work, variable should be assigned null explicitly somewhere. And that's impossible, because try block could throw an exception in the first line.

Whatever asks you to make the variable final - ignore it.

You can make it work like this. As some other answers are explaining, you can't assign value for final variable twice.

You can make it work like this

void yyyyyy(final ActionEvent event) {
    Scanner enter = null;
    try {
        enter = new Scanner("/");
    } catch (final Exception exception) {

    } finally {
        enter.close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM