gpt4 book ai didi

Java - 找不到 .class 问题

转载 作者:搜寻专家 更新时间:2023-11-01 01:23:00 25 4
gpt4 key购买 nike

我有以下代码,

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 expected”。谁能帮我解决这个问题是什么以及如何解决?

最佳答案

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

if (condition)
int x = 10;

你不能在 Java 中这样做。您不能将变量声明用作if 主体中的单个语句...大概是因为变量本身毫无意义;唯一的目的是解决用于赋值的表达式的副作用。

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

if (condition) {
int x = 10;
}

还是没用,但至少能编译...

编辑:回应评论,如果您需要在 if block 中使用变量,您需要在之前声明它if block ,并确保它在读取值之前已初始化。例如:

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

关于Java - 找不到 .class 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10324564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com