115

我想知道是否可以像这样在条件运算符中为变量赋值:

if((int v = someMethod()) != 0) return v;

有没有办法在 Java 中做到这一点?因为我知道在while某些条件下这是可能的,但我不确定我是否对 if 语句做错了,或者它是否不可能。

4

9 回答 9

197

变量可以被赋值,但不能在条件语句中声明:

int v;
if((v = someMethod()) != 0) return true;
于 2013-04-22T13:42:53.377 回答
28

您可以在 an 内分配,但不能声明if

尝试这个:

int v; // separate declaration
if((v = someMethod()) != 0) return true;
于 2013-04-22T13:47:16.867 回答
21

an assignment returns the left-hand side of the assignment. so: yes. it is possible. however, you need to declare the variable outside:

int v = 1;
if((v = someMethod()) != 0) {
    System.err.println(v);
}
于 2013-04-22T13:43:39.263 回答
8

Yes, you can assign the value of variable inside if.

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===.

It will be better if you do something like this:

int v;
if((v = someMethod()) != 0) 
   return true;
于 2013-04-22T13:41:42.903 回答
2

我相信您的问题是由于您在测试中定义了变量 v 。正如@rmalchow 所解释的,它会让你把它改成

int v;
if((v = someMethod()) != 0) return true;

还有另一个变量范围的问题。即使您尝试的方法有效,那又有什么意义呢?假设您可以在测试中定义变量范围,您的变量 v 将不存在于该范围之外。因此,创建变量并分配值将毫无意义,因为您将无法使用它。

变量只存在于它们创建的范围内。由于您要分配值以供以后使用,因此请考虑创建变量的范围,以便可以在需要的地方使用它。

于 2013-04-22T13:52:19.373 回答
2

是的,有可能做到。考虑下面的代码:

public class Test  
{        
    public static void main (String[] args)       
    {       
        int v = 0;          
        if ((v=dostuff())!=0)            
        {          
            System.out.printf("HOWDY\n");          
        }             
    }                
    public static int dostuff()       
    {             
        //dosomething              
        return 1; 
    }       
}          

我希望这能满足你的问题。

于 2013-04-22T13:57:11.190 回答
1

You can assign a variable inside of if statement, but you must declare it first

于 2013-04-22T13:42:55.157 回答
1

Yes, it is possible to assign inside if conditional check. But, your variable should have already been declared to assign something.

于 2013-04-22T13:43:51.867 回答
0

Because I know it's possible in while conditions, but I'm not sure if I'm doing it wrong for the if-statement or if it's just not possible.

HINT: what type while and if condition should be ??

If it can be done with while, it can be done with if statement as weel, as both of them expect a boolean condition.

于 2013-04-22T13:43:18.970 回答