简体   繁体   中英

getMethod return null java

I wrote getMethod in the file MovieReader and if I print this method inside this file everything is working well.

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

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. When you create a new MovieReader object, the main() method is not executed, so the text field is not initialized.

You can create a static loader method in MovieReader and move the code from main() to there, like this:

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() :

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.

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.

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.

The longer answer, how you should actually do it: You probably come from a scripting background like 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.

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. Then have User.main() call that method as well, before calling getText().

Don't put all the logic in main

First of all, you should call static getText() method with class name.

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.

Refer the following fixed code:

MovieReader class

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.

main() method and getText() method of the class MovieReader are independent of each other. 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. 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,

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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