【发布时间】:2020-03-25 20:40:24
【问题描述】:
我使用 Eclipse 进行编程,它告诉我是否要输出“输入字符串”
无法对非静态字段 Input 进行静态引用
为什么finally块中的变量是静态的?
import java.util.Scanner;
public class NameSort {
String Input;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Inupt some Text");
while (sc.hasNextLine()){
String Input = sc.nextLine();
System.out.println(Input);
if (Input.toLowerCase().equals("ende")) {
System.exit(0);
sc.close();
}
}
} finally {
if (sc != null)
sc.close();
System.out.print(Input);
}
}
}
【问题讨论】:
-
因为方法是
static。 --- 仅供参考:while循环内的Input局部变量与Input字段完全不同,因为这意味着该字段永远不会被分配,因此将始终为null在他finally块中。 -
您在两个不同的范围内定义了两次
Input。从重命名这些变量中的任何一个开始,然后也许答案会更清楚。 -
仅供参考:
sc不可能在finally块中成为null。 -
您不应该关闭
InputStream为System.in的Scanner,即使IDE 告诉您应该这样做。
标签: java try-finally