我有以下代码,
class AA {
public static void main(String[] args) {
long ll = 100 ;
AA1 a1 = new AA1() ;
if(ll == 100) // Marked line
long lls [] = a1.val(ll);
}
}
class AA1 {
public long [] val (long ll1) {
long [] val = new long []{1 , 2, 3};
return val ;
}
}
在没有标记行的情况下正确执行。但是,给出错误".class预期"与标记行。任何人都可以帮助我是什么问题以及如何解决这个问题?
您问题的简化版本:
if (condition)
int x = 10;
你不能在Java中做到这一点。不能将变量声明用作if
体中的单个语句...大概是因为变量本身毫无意义;唯一的目的是用于赋值的表达式的副作用。
如果您真的想要毫无意义的声明,请使用大括号:
if (condition) {
int x = 10;
}
它仍然没用,但至少它会编译...
编辑:响应注释,如果您需要在if
块之外使用该变量,则需要在if
块之前声明它,并确保在读取值之前对其进行初始化。例如:
// Note preferred style of declaration, not "long lls []"
long[] lls = null; // Or some other "default" value
if (ll == 100) {
// I always put the braces in even when they're not necessary.
lls = a1.val(ll);
}
// Now you can use lls
或:
long[] lls;
if (ll == 100) {
lls = a1.val(ll);
} else {
// Take whatever action you need to here, so long as you initialize
// lls
lls = ...;
}
// Now you can use lls
或者可能使用条件表达式:
long[] lls = ll == 100 ? a1.val(ll) : null;
正如Jon Skeet指出的,这(1):
if(ll == 100)
long lls [] = a1.val(ll);
不会编译,因为它将声明用作单个语句。
这 (2):
if(ll == 100){
long lls [] = a1.val(ll);
}
将编译,因为编译器并不真正关心{}
内部的内容 - 就if
而言,它是一个块。这也是毫无意义的,因为它相当于(3):
if(ll == 100)
a1.val(ll);
但是,当我看到(1)时,通常看起来实际含义是:
long lls [];
if(ll == 100)
lls = a1.val(ll);