在 if 语句中分配变量值

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

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

在 Java 中有什么方法可以做到这一点吗?因为我知道在 while条件下这是可能的,但是我不确定 if 语句是否做错了,或者这是不可能的。

212206 次浏览

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

我不建议这么做。问题是,这看起来像一个常见的错误,您尝试比较值,但使用一个单一的 =而不是 =====

如果你这样做会更好:

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

Variables can be assigned but not declared inside the conditional statement:

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

您可以在 if语句中分配一个变量,但是必须首先声明它

因为我知道在这种情况下是有可能的,但我不确定 我对 if 语句的处理是错误的,或者这是不可能的。

提示: while 和 if 条件应该是什么类型? ?

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

赋值返回赋值的左边。所以,是的。有可能。但是,您需要在外部声明变量:

int v = 1;
if((v = someMethod()) != 0) {
System.err.println(v);
}

是的,如果条件检查可以在里面分配。但是,您的变量应该已经声明为赋值。

你可以在 if中使用 assign,但不能使用 声明:

试试这个:

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

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

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

There is also another issue of variable scope. Even if what you tried were to work, what would be the point? Assuming you could define the variable scope inside the test, your variable v would not exist outside that scope. Hence, creating the variable and assigning the value would be pointless, for you would not be able to use it.

变量只存在于它们创建的范围内。因为您要为之后使用它分配值,所以要考虑创建变量的作用域,以便在需要的地方使用它。

是的,这是可能的。考虑下面的代码:

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;
}
}

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