【问题标题】:Why does a variable need to be static in the finally-block [duplicate]为什么变量需要在finally块中是静态的[重复]
【发布时间】: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
  • 您不应该关闭InputStreamSystem.inScanner,即使IDE 告诉您应该这样做。

标签: java try-finally


【解决方案1】:

在 Java 中,您不能从 static 方法使用/调用非静态变量/方法。另外,除了下面的代码,你的其他代码都没用:

import java.util.Scanner;

public class NameSort {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input;
        System.out.println("Inupt some Text");
        while (!(input = sc.nextLine()).equals("ende")) {
            System.out.println(input);
        }
    }
}

示例运行:

Inupt some Text
hello
hello
hi
hi
ende

【讨论】:

    【解决方案2】:

    这与finally 块无关,在Java 中你不能从static 方法访问非静态成员或方法。

    如果您想从main 访问它,您应该将Input 设为静态。

    【讨论】:

      猜你喜欢
      • 2013-08-05
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 2014-08-27
      • 2020-01-15
      • 2020-10-22
      相关资源
      最近更新 更多