gpt4 book ai didi

java - 我可以通过 if else/语句声明变量吗

转载 作者:行者123 更新时间:2023-12-02 04:14:56 25 4
gpt4 key购买 nike

可以通过 if/else 语句声明变量吗?

int num1;
int num2;
int num3;

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

最佳答案

您可以在 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.

使用条件运算符(也称为三元运算符)通常比在 if/else 中赋值更好

int num3 = num1 <= num2 ? num1 - num2 : num2 - num1;

关于java - 我可以通过 if else/语句声明变量吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com