返回方法中的另一个类的方法。导致java.lang.NullPointerException

时间:2015-10-25 18:05:48

标签: java class return

我是java新手,我正在创建通用社交媒体网站。我的用户类能够创建一个" Post"类。在尝试查看这些帖子时,我收到了上述错误。我想在类中创建一个方法,以便用户类查看它与之后的类相关的字符串。

   import java.util.Scanner;
public class User {
  private String password, address;
  private Post myPost;
  private int age;
  public String userName;

public User (String u, String p, String l, int a) {
   userName = u;
   password = p;
   address = l;
   age = a;
}

  public String viewLoginName ( ) {
    return userName;
  }

  public String viewPassword ( ) {
    return password;
  }

  public String viewAddress ( ) {
    return address;
  }

  public int viewAge ( ) {
    return age;
  }

  public Post createPost ( ) {
    Scanner reader = new Scanner ( System.in );
    String message;
    System.out.println("What would you like to share? ");
    message = reader.next ( );
    myPost = new Post(userName + ": " + message);
    return myPost;
  }
  public String viewMyPost()
   { 
     return myPost.viewPost();
  }
//the new method meant to allow users to view other users post
 public String viewUserPost(String user)
     {
      return user.viewMyPost();
     } 
}




//Post Class

import java.util.Scanner;
public class Post {
    private String message, acknowledged = "";
    //Scanner reader = new Scanner ( System.in );
    //message = reader.nextString ( );

    public Post(String m) {
        message = m;
    }
    public String viewPost() {
        return message;
    }

    public String acknowledge() {
        System.out.println("What is your username?");
        Scanner reader = new Scanner(System. in );
        String acknowledger;
        acknowledger = reader.next();
        acknowledged = acknowledged + acknowledger + ',';
        return acknowledged;

    }
}

1 个答案:

答案 0 :(得分:1)

您通过在方法中重新声明myPost变量来隐藏它。这使类字段为null。不要重申它。

public String createPost() {
    Scanner reader = new Scanner(System. in );
    String message;
    System.out.println("What would you like to share? ");
    message = reader.next();

    // Post myPost = new Post(userName + ": " + message);
    myPost = new Post(userName + ": " + message); // note the difference?

    return "";
}

作为一个侧面推荐,我会从您的User类中获取所有用户界面代码,因为它不属于那里,并且您可能会通过一遍又一遍地创建Scanner对象来解决资源问题。相反,UI代码属于其自己的类中的其他位置,您应该考虑为createPost方法提供名为message的String参数。

此外,我还会考虑删除Post变量本身及其getter方法,并且只需让createPost(String message)方法在调用时返回Post对象。现在它返回一个无用的空字符串,这对你或你的用户没有帮助。

public Post createPost(String message) {
    return new Post(userName + ": " + message); 
}