gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:00:54 25 4
gpt4 key购买 nike

我是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;

}
}

最佳答案

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

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 的字符串参数。

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

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

关于java - 在方法中返回另一个类的方法。导致 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33333104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com