简体   繁体   English

在条件内重新分配Java变量

[英]Reassigning a Java variable within a conditional

I've got a variable, which is initialized and then dynamically reassigned in a conditional; 我有一个变量,该变量被初始化,然后在有条件的情况下动态地重新分配。 as such: 因此:

int a;

if(b > 5) {
    int a = 10;
} else {
    int a = 1;
}

It gives me this error: 它给了我这个错误:

/path/to/file:4 a is already defined in int a = null;

Why can't I reassign this variable? 为什么不能重新分配此变量?

When you write 当你写

int a;

this is the declaration of variable. 这是变量的声明。 And if you try to again write it the same way in the same scope and as the variable already exists so compiler throws an error. 而且,如果您尝试在相同的作用域中以相同的方式再次写入它,并且变量已经存在,则编译器将引发错误。

You need not to re-define the variable a , just re-assign it like this: 您无需重新定义变量a ,只需像这样重新分配它:

int a = 0; // note that you need to initialize the local variables before using 

if(b > 5) {
     a = 10;
} else {
     a = 1;
}

You're actually redeclaring variable a , not reassigning its value. 您实际上是在重新声明变量a ,而不是重新分配其值。

Try 尝试

a = 10;

instead of 代替

int a = 10;

是时候使用嵌入式条件运算符(“三元运算符”)了:

 int a = (b > 5) ? 10 : 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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