如何在 Java 中的 if 语句中为变量赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3594427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:20:52  来源:igfitidea点击:

How can you assign a variable a value inside a if statement in Java

java

提问by Dananjaya

I need to do something like this,

我需要做这样的事情,

if (first_var > second_var)
  int difference = first_var - second_var;
if (first_var < second_var)
  int difference = second_var - first_var;

When I try to compile this, an error comes stating the variable 'difference' may not have been initialized. Making the variable 'difference' global doesn't help either.

当我尝试编译它时,会出现一个错误,指出变量“difference”可能尚未初始化。使变量 'difference' 成为全局变量也无济于事。

采纳答案by polygenelubricants

The issues that you need to learn are:

你需要学习的问题是:

  • The scope of variables
  • Block declaration and how that creates new scopes
  • Why you should prefer to use {...}block for ifstatements
  • How to guarantee definite assignment
  • When to use if-elseinstead of if (something) {...} if (!something) {...}
  • 变量范围
  • 块声明以及如何创建新范围
  • 为什么你应该更喜欢使用语句{...}if
  • 如何保证明确的分配
  • 何时使用if-else而不是if (something) {...} if (!something) {...}

By the way, the idiomatic way to find the difference of two values is:

顺便说一句,找到两个值的差异的惯用方法是:

int difference = Math.abs(firstVar - secondVar);

Do note that Math.abshas a corner case: when the argument is Integer.MIN_VALUE, the returned value is Integer.MIN_VALUE. That's because -Integer.MIN_VALUE == Integer.MIN_VALUE. The issue here is 32-bit two's complement representation of numbers.

请注意,Math.abs有一个极端情况:当参数为 时Integer.MIN_VALUE,返回值为Integer.MIN_VALUE。那是因为-Integer.MIN_VALUE == Integer.MIN_VALUE. 这里的问题是数字的 32 位二进制补码表示。

References

参考



Attempt #1: Declaring before the if

尝试 #1:在 if

Here's one attempt to fix the snippet, by declaring the variable before the if

这是修复代码段的一种尝试,方法是在 if

int difference;
if (first_var > second_var) {
  difference = first_var - second_var;
}
if (first_var < second_var) {
  difference = second_var - first_var;
}

// note: difference is not definitely assigned here!
//           (but at least it's in scope!)

We now have a problem with definite assignment: if first_var == second_var, the variable differenceis still not assigned a value.

我们现在有一个明确赋值的问题:如果first_var == second_var,变量difference仍然没有赋值。



Attempt #2: Initializing at declaration

尝试 #2:在声明时初始化

Here's a second attempt:

这是第二次尝试:

int difference = 0;
if (first_var > second_var) {
  difference = first_var - second_var;
}
if (first_var < second_var) {
  difference = second_var - first_var;
}

// note: difference is in scope here, and definitely assigned

Beginners tend to do this, but this precludes the possibility of making differencea finallocal variable, because it's possibly assigned value twice.

初学者往往要做到这一点,但是这妨碍制造的可能性,difference一个final局部变量,因为它可能分配的值的两倍。



Attempt #3: if-else

尝试#3: if-else

Here's a better attempt:

这是一个更好的尝试:

final int difference;
if (first_var > second_var) {
  difference = first_var - second_var;
} else {
  difference = second_var - first_var;
}

// note: difference is in scope, and is definitely assigned here,
//       (and declared final)

There are still ways to improve on this.

在这方面仍有改进的方法。



Attempt #4: The ternary/conditional operator

尝试 #4:三元/条件运算符

Once you're more comfortable with the language and programming, you may use the following idiom:

一旦您对语言和编程更加熟悉,您可以使用以下习语:

final int difference = (first_var > second_var) ? first_var - second_var
                                                : second_var - first_var;

This uses the ?:ternary/conditional operator. Do be careful with this operator; it has some behaviors that may be surprising, and it definitely can be abused. Use carefully, judiciously, idiomatically.

这使用?:三元/条件运算符。一定要小心这个运营商;它有一些可能令人惊讶的行为,并且绝对可以被滥用。谨慎、明智、惯用地使用。

References

参考

回答by Peter Alexander

You have two options:

您有两个选择:

  1. Do the condition on one line using the ternary operator ?:

    int difference = first_var > second_var ? first_var - second_var : second_var - first_var;
    
  2. Declare the variable up front, then do the condition.

    int difference = 0;
    if (first_var > second_var)
      difference = first_var - second_var;
    if (first_var < second_var)
      difference = second_var - first_var;
    
  1. 使用三元运算符在一行上执行条件吗?:

    int difference = first_var > second_var ? first_var - second_var : second_var - first_var;
    
  2. 预先声明变量,然后执行条件。

    int difference = 0;
    if (first_var > second_var)
      difference = first_var - second_var;
    if (first_var < second_var)
      difference = second_var - first_var;
    

回答by user151019

You can only declare a variable in one place.

您只能在一个地方声明一个变量。

The basic solution is

基本的解决办法是

int difference;
if (first_var > second_var)
  difference = first_var - second_var;
if (first_var < second_var)
  difference = second_var - first_var;

However in this case you can use inline ?: operator

但是在这种情况下,您可以使用内联 ?: 运算符

int difference = (first_var > second_var) ? 
  first_var - second_var : second_var - first_var;

回答by Matti Virkkunen

It's because the variable might indeed not get initialized. In reality if first_varand second_varare equal to each other, it wouldn't get initialized. In addition to that, the compiler probably isn't smart enough to figure it out even if you added a third if. Move the declaration outside the ifs and initialize it to a value on that line as well.

这是因为变量可能确实没有被初始化。实际上,如果first_varsecond_var彼此相等,则不会被初始化。除此之外,即使您添加了第三个if. 将声明if移到 s之外并将其初始化为该行上的一个值。

int difference = 0;
if (first_var > second_var)
    difference = first_var - second_var;
if (first_var < second_var)
    difference = second_var - first_var;

However, I'd just do

但是,我只想做

int difference = Math.abs(first_var - second_var);

回答by Vivien Barousse

First, you have to define tour variable "difference" outside your ifs statements:

首先,您必须在 ifs 语句之外定义游览变量“difference”:

int difference;
if (first_var > second_var)
    difference = first_var - second_var;
if (first_var < second_var)
    difference = second_var - first_var;

Then, the compiler can't be sure that your variable will have a value once both ifs statements are executed. For example, if first_var and second_var have the same value, difference will not be assigned. So, if you try to use your variable, you'll have a compile time error.

然后,一旦两个 ifs 语句都被执行,编译器就不能确定你的变量会有一个值。例如,如果 first_var 和 second_var 具有相同的值,则不会分配差异。因此,如果您尝试使用变量,则会出现编译时错误。

To resolve this, you have two solutions:

要解决此问题,您有两种解决方案:

The first solution is to give your variable a default value, which will be used if no other conditions is completed:

第一个解决方案是给你的变量一个默认值,如果没有其他条件完成,它将被使用:

int difference = 0;
if (first_var > second_var)
    difference = first_var - second_var;
if (first_var < second_var)
    difference = second_var - first_var;

The other solution is to use else if statements. When using else if statements, the compiler is able to determine if your variable will be assigned in all cases:

另一种解决方案是使用 else if 语句。使用 else if 语句时,编译器能够确定您的变量是否在所有情况下都将被赋值:

int difference;
if (first_var > second_var) {
    difference = first_var - second_var;
} else if (first_var < second_var) {
    difference = second_var - first_var;
} else {
    difference = 0;
}

回答by lala

You can indeed assign a variable inside an if statement, but you cannot initialize it inside an if statement. In plain English, you can give a variable a value inside an if statement, but you cannot create a variable inside an if statement. The reason for this is because there is a possibility that the code inside the if statement will never run if the if conditions are never met.

您确实可以在 if 语句中分配变量,但不能在 if 语句中初始化它。简单来说,您可以在 if 语句中为变量赋值,但不能在 if 语句中创建变量。这样做的原因是因为如果从未满足 if 条件,则 if 语句中的代码可能永远不会运行。

Here's how I would have written that code:

这是我编写该代码的方式:

int difference = 0;

if (first_var > second_var)
   difference = first_var - second_var;
else if (first_var < second_var)
   difference = second_var - first_var;

回答by CJ Goggin

The reason why it may not have been initialized is you accounted for A < B, B < A, but not A == B. Account for that:

它可能没有被初始化的原因是你考虑了 A < B, B < A,但不是 A == B。考虑到:

if (first_var > second_var)
  int difference = first_var - second_var;
if (first_var < second_var)
  int difference = second_var - first_var;
if (first_var == second_var)
  int difference = 0;