简体   繁体   English

getMethod返回null java

[英]getMethod return null java

I wrote getMethod in the file MovieReader and if I print this method inside this file everything is working well. 我在文件MovieReader中编写了getMethod,如果我在此文件中打印此方法,则一切工作正常。

import java.io.BufferedReader; // scanner
import java.io.FileReader;
public class MovieReader {

    private static String text;

    public static void main(String args[]) throws Exception {
        FileReader file = new FileReader("C:/Users/krystian/Desktop/filmDateBaseProject/movies.txt");
        BufferedReader reader = new BufferedReader(file);
        text = "";
        String line = reader.readLine();
        while(line != null) {
            text+= line +"\n";
            line=reader.readLine();
        }
        reader.close();
        System.out.println(getText()); // This method works
    }

    public static String getText() {
        return text;
    }

}

But when I'm trying to call this method from other file it's printing null 但是,当我尝试从其他文件调用此方法时,它的输出为null

public class Userr{

   public static void main(String args[]){

      MovieReader user = new MovieReader();

      System.out.println(user.getText());

  }
}

Can you help me with it? 你能帮我吗?

In the MovieReader class you load the file and fill the contents of text in the main() method. MovieReader类中,您加载文件并在main()方法中填充text内容。 When you create a new MovieReader object, the main() method is not executed, so the text field is not initialized. 创建新的MovieReader对象时,不会执行main()方法,因此不会初始化text字段。

You can create a static loader method in MovieReader and move the code from main() to there, like this: 您可以在MovieReader创建一个静态加载器方法, MovieReader代码从main()移到那里,如下所示:

public static void loadMovieInfo() {
    FileReader file = new FileReader("C:/Users/krystian/Desktop/filmDateBaseProject/movies.txt");
    ... // rest of the code
    reader.close();
}

Just call this before trying to call getText() : 在尝试调用getText()之前,只需调用此方法即可:

MovieReader.loadMovieInfo();
System.out.println(MovieReader.getText());

If you want the file to be loaded and the content of text to be filled when the object is created, you can turn text into an instance variable and load the file info in the MovieReader constructor. 如果要在创建对象时加载文件并填充text内容,则可以将text转换为实例变量,然后在MovieReader构造函数中加载文件信息。

Example: 例:

public class MovieReader {
    private String text;

    public MovieReader() {
        FileReader file = new FileReader("C:/Users/krystian/Desktop/filmDateBaseProject/movies.txt");
        BufferedReader reader = new BufferedReader(file);
        this.text = "";
        String line = reader.readLine();
        while(line != null) {
            this.text += line +"\n";
            line=reader.readLine();
        }
        reader.close();
    }

    public String getText() {
        return this.text;
    }
}

Then this should work: 然后这应该工作:

MovieReader user = new MovieReader();
System.out.println(user.getText());

Also, a couple of observations: 另外,有以下几点观察:

  • Static methods belong to the class (not to a particular object), and should be called with the name of the class: 静态方法属于该类(而不是特定对象),并且应使用该类的名称来调用:

     MovieReader.getText() 
  • You should use a StringBuilder ( docs here ) instead of String concatenation to fill the contents of the text variable. 您应该使用StringBuilderdocs此处 )代替String串联来填充text变量的内容。

Try this one. 试试这个。

import java.io.BufferedReader; // scanner
import java.io.FileReader;
public class MovieReader {

    private static String text;

    public static String getText() {

        FileReader file = new FileReader("C:/Users/krystian/Desktop/filmDateBaseProject/movies.txt");
        BufferedReader reader = new BufferedReader(file);
        text = "";
        String line = reader.readLine();
        while(line != null) {
            text+= line +"\n";
            line=reader.readLine();
        }
        reader.close();
        System.out.println(getText()); // This method works
        return text;
    }

}

public class Userr{

   public static void main(String args[]){

      MovieReader user = new MovieReader();

      System.out.println(user.getText());

  }
}

The fast and dirty fix: Call the MovieReader.main method. 快速而肮脏的修复方法:调用MovieReader.main方法。

The longer answer, how you should actually do it: You probably come from a scripting background like python. 更长的答案是,您应该如何实际执行:您可能来自像python这样的脚本背景。 What you did here was to create two scripts, basically, wrapped in classes. 您在这里所做的基本上是创建两个包装在类中的脚本。 When you call java, you have one class as entry point, whose main method is called. 调用java时,有一个类作为入口点,其主方法被调用。

So you created one script that loads a file, and another script that reads it, and your expectation is that both main methods are called. 因此,您创建了一个加载文件的脚本,另一个创建了读取文件的脚本,您的期望是调用了两个主要方法。 You need to go back to design! 您需要返回设计!

The better way would be to only have a minimal main() in MovieReader, and instead have a method like readMovies(), which the main() calls. 更好的方法是在MovieReader中仅具有最小的main(),而使用诸如readMovies()之类的方法,由main()调用。 Then have User.main() call that method as well, before calling getText(). 然后,在调用getText()之前,也让User.main()调用该方法。

Don't put all the logic in main 不要把所有逻辑都放在主要

First of all, you should call static getText() method with class name. 首先,您应该使用类名调用静态getText()方法。

MovieReader.getText()

Second, default value of static string: 二,静态字符串的默认值:

It's initialized to null if you do nothing, as are all reference types.

As, you are not doing anything that's why the value of text is null. 因为,您没有做任何事情,所以text的值为null。

Refer the following fixed code: 请参考以下固定代码:

MovieReader class MovieReader类

public class MovieReader {

 private static String text;

 public static void main(String args[]) throws Exception {
    FileReader file = new FileReader("C:/Users/krystian/Desktop/filmDateBaseProject/movies.txt");
    BufferedReader reader = new BufferedReader(file);
    text = "";
    String line = reader.readLine();
    while(line != null) {
        text+= line +"\n";
        line=reader.readLine();
    }
    reader.close();
    System.out.println(getText()); // This method works
 }

 public static String getText() {
    return text;
 }

}

Userr class: 用户类:

public class Userr{

   public static void main(String args[]){


      try {
        MovieReader.main(null);
    } catch (Exception e) {

        e.printStackTrace();
    }

      System.out.println(MovieReader.getText());

  }
}

Assuming that you are running the main() method of Userr class. 假设您正在运行Userr类的main()方法。

main() method and getText() method of the class MovieReader are independent of each other. MovieReader类的main()方法和getText()方法彼此独立。 If you are calling getText() method, it will return the value of text variable without any operations on it, cos operations of main() method [ of MovieReader class ] are not going to execute. 如果要调用getText()方法,它将返回text变量的值,而无需对其进行任何操作MovieReadermain()方法的cos操作将不会执行。 That's why you are not getting intended result. 这就是为什么您没有得到预期的结果。

try to re factor your code as below. 尝试如下重构您的代码。

public class Movie {

    public static void main(String[] args) {
        MovieReader user = new MovieReader();
        String file = "C:/Users/krystian/Desktop/filmDateBaseProject/movies.txt";
        System.out.println(user.getText(file));
    }
}

and the MovieReader class, 还有MovieReader类,

class MovieReader {

    private String text;

    String getText(String fileName) {
        FileReader file;
        file = null;
        try {
            file = new FileReader(fileName);
            BufferedReader reader = new BufferedReader(file);
            text = "";
            String line = reader.readLine();
            while (line != null) {
                text += line + "\n";
                line = reader.readLine();
            }
            reader.close();
            return text;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MovieReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MovieReader.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                file.close();
            } catch (IOException ex) {
                Logger.getLogger(MovieReader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }
}

its always a good practice to use exception handling. 使用异常处理始终是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM