我可以通过if else / statement声明变量

时间:2015-10-29 21:52:32

标签: java

你能通过if / else语句声明一个变量吗?

int num1;
int num2;
int num3;

if (num1 <= num2){
    num3 = (num1-num2);
}else{
    num3 = (num2-num1);
}

1 个答案:

答案 0 :(得分:2)

您可以在if / else:

分配变量
self.completion(self);

您还可以在if / else中声明变量,但之后不会显示。

int num1 = 2;
int num2 = 3;
int num3;                // This is a declaration

if (num1 <= num2){
    num3 = (num1-num2);  // This is an assignment
}else{
    num3 = (num2-num1);  // This is an assignment
}
// We can use num3 here

如果在if / else中分配变量,请确保保证分配变量。

int num1 = 2;
int num2 = 3;

if (num1 <= num2){
    int num3 = (num1-num2);  // This is a declaration and assignment in one.
}else{
    int num3 = (num2-num1);  // So is this
}
// We can't use num3 here.

使用条件运算符(也称为三元运算符)而不是在if / else中分配

通常更好
int num1 = 2;
int num2 = 3;
int num3;

if (num1 <= num2){
    num3 = (num1-num2);  
}else if (num1 == 9) {
    num3 = (num2-num1);  
}
// We can't use num3 here because the compiler can't be sure that one of the assignments happened.