如何将方法中的变量声明为static(java)

时间:2014-06-01 23:22:44

标签: java nullpointerexception static-methods static-variables

我正在创建一个使用多个类的加密/解密程序。我有一个类是UI,并使用带有文件选择器的JFrame表单,以及另一个加密/解密所选文件的类。当我尝试使用加密类中的UI类中声明的java.io.File变量时遇到问题。

文件选择器代码:

public static void actionEncrypt() {
    encrypt = true;
    int retVal = selectFile.showOpenDialog(null);
    if (retVal == selectFile.APPROVE_OPTION) {
        java.io.File file = selectFile.getSelectedFile();
        System.out.println(file);
        Crypt.encrypt();
    }
}

变量声明代码:

public static boolean encrypt;
public static java.io.File file;

文件阅读代码:

public static void encrypt() {
    System.out.println(MainUI.file);
    try {
        Scanner filescan = new Scanner(MainUI.file);
        int count = 0;
        while (filescan.hasNextLine()) {
            count++;
            filescan.nextLine();
        }
    } catch (FileNotFoundException e) {
        System.out.println("File not found!");
    }
}

当我运行此代码时,我得到NullPointerException,因为文件读取代码运行时File变量的值为null。这是因为它在变量声明代码中声明为static,它会覆盖方法actionEncrypt中声明的值。如果我不将变量设为静态,当我尝试从其他类访问变量时,我得到Cannot find symbol。但是,我无法在方法actionEncrypt中将变量声明为静态,因为它为我提供了illegal start of expression。有没有人知道如何在不隐藏字段的情况下将方法中的变量声明为静态,或者在另一个类中使用File变量的任何其他方式?

提前致谢,

圣地亚哥

1 个答案:

答案 0 :(得分:1)

我想我在你的代码中看到了错误。

更改以下行,以便初始化MainUI.file。目前,您正在创建一个名为file的局部变量,并初始化该变量而不是MainUI.file,这是您可能要初始化的内容。

    java.io.File file = selectFile.getSelectedFile();

将其替换为。

    MainUI.file = selectFile.getSelectedFile();