gpt4 book ai didi

java - if 语句 "not a statement"?

转载 作者:行者123 更新时间:2023-12-03 01:28:38 26 4
gpt4 key购买 nike

示例代码:

public class SalCal {
public static void main(String[] args) {
int a=0;
if (a > 1)
String string = "fds";//hint:not a statement
}
}

Intellij IDEA 提示 String string = "fds";

not a statement

但是如果我在 String string = "fds"; 的两边添加大括号,它就不会像以前那样提示了。为什么?

最佳答案

Intellij IDEA 这么说是因为它不是一个声明。这是一个声明1

当你添加大括号时,你就将它变成了一个 block 语句......这是一个语句。

但这就是问题所在。如果这段代码是合法的,那么它就没用了。

  if (a> 1)
String string = "fds";
为什么?因为声明的范围必须在 if 语句结束时结束。您将声明一个 不能使用的变量。

<小时/>

这里有几个替代方案:

1) 此版本在 if block 中声明变量

  if (a> 1) {
String string = "fds";
// you can use 'string' here
}
// ... but not here, because it is now out-of-scope.

2) 此版本在 if 语句之前声明并初始化变量,并在 if 中为其分配新值:

  String string = "asdf";
if (a> 1) {
string = "qwerty"; // assignment, not declaration
}
// OK to use 'string' here.
<小时/>

@Maroun 的回答给出了您所编写的内容不是有效 Java 代码的技术原因。

<小时/>

1 - 事实上,Intellij IDEA 编译器“与事实不符”。事实上,JLS 称之为“局部变量声明语句”。因此,从技术上讲,它是一种“声明”……但它是一种特殊的声明,不能在普通声明可以使用的所有上下文中使用。

关于java - if 语句 "not a statement"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35124988/

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