Java - .class未找到问题

Arp*_*sss 4 java

我有以下代码,

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

}
Run Code Online (Sandbox Code Playgroud)

没有标记线正确执行.但是,给出带有标记线的错误".class expected".任何人都可以帮助我解决问题以及如何解决这个问题?

Jon*_*eet 9

基本上这是您问题的简化版本:

if (condition)
    int x = 10;
Run Code Online (Sandbox Code Playgroud)

你不能用Java做到这一点.你不能将变量声明用作if正文中的单个语句...大概是因为变量本身是没有意义的; 唯一的目的是用于赋值的表达式的副作用.

如果你真的想要无意义的声明,请使用大括号:

if (condition) {
    int x = 10;
}
Run Code Online (Sandbox Code Playgroud)

它仍然没用,但至少它会编译......

编辑:应对评论,如果你需要使用的变量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
Run Code Online (Sandbox Code Playgroud)

要么:

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
Run Code Online (Sandbox Code Playgroud)

或者可能使用条件表达式:

long[] lls = ll == 100 ? a1.val(ll) : null;
Run Code Online (Sandbox Code Playgroud)