Java初学者的烦恼;从方法调用。希望是小问题

标签 java variables methods

我正在开发这个小项目,我获得了驱动程序,并且必须为其编写帮助程序类。

驱动程序:

public class MyBookDriver {

private static final Scanner KBD = new Scanner(System.in);

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {        
    // Constructors
    MyBookAccount bbSheldon = new MyBookAccount("Sheldon", true);
    MyBookAccount bbPenny = new MyBookAccount("Penny", false);
    MyBookAccount bbAmy = new MyBookAccount("Amy", "Montreal", true);
    MyBookAccount bbLeonard = new MyBookAccount("Leonard");
    System.out.println("\n" + MyBookAccount.getNumAccounts()
            + " MyBook accounts have been created.");

    // Mybook ID
    System.out.println("\nMyBook Accounts:");
    System.out.println("    Sheldon's ID: " + bbSheldon.ID);
    System.out.println("    Penny's ID: " + bbPenny.ID);
    System.out.println("    Amy's ID: " + bbAmy.ID);
    System.out.println("    Leonard's ID: " + bbLeonard.ID);
    pause();

    // logged in
    System.out.println("\nMyBook Accounts:");
    System.out.println("    Sheldon is " 
            + (bbSheldon.isLoggedIn() ? "" : "not ") + "logged in");
    System.out.println("    Penny is " 
            + (bbPenny.isLoggedIn() ? "" : "not ") + "logged in");
    System.out.println("    Amy is " 
            + (bbAmy.isLoggedIn() ? "" : "not ") + "logged in");
    System.out.println("    Leonard is " 
            + (bbLeonard.isLoggedIn() ? "" : "not ") + "logged in");
    pause();

    //post a wall message 
    System.out.println("\nPosting wall update:");
    bbSheldon.setWallPost("I like flags!");
    bbPenny.setWallPost("Looking for a job.");
    bbLeonard.setWallPost("I'm just hoping I can date a girl "
            + "from next door.");
    System.out.println("    Sheldon's: " + bbSheldon.getWallPost() + "\n"
            + "    Penny's: " + bbPenny.getWallPost() + "\n"
            + "    Amy's: " + bbAmy.getWallPost() + "\n"
            + "    Leonard's: " + bbLeonard.getWallPost() + "\n");
    pause();

    //Sending messages
    System.out.println("\nSending messages:");
    bbLeonard.sendMessage(bbPenny, "Will you go out with me tonight?");
    bbAmy.sendMessage(bbSheldon, "Neuroscience is a real science.");
    bbPenny.sendMessage(bbAmy, "What a nice picture.");
    checkMessages(bbSheldon);
    checkMessages(bbPenny);
    checkMessages(bbAmy);
    checkMessages(bbLeonard);
    pause();

    //toString
    System.out.println("\nDisplaying info:");
    System.out.println(bbSheldon);
    System.out.println(bbPenny);
    System.out.println(bbAmy);
    System.out.println(bbLeonard);
    pause();
}

private static void checkMessages(MyBookAccount user) {
    MyBookAccount aFriend;
    aFriend = user.getFriend();
    if (aFriend != null) {
        System.out.println("    " + user.getName() + "'s message from " 
                + aFriend.getName()
                + " is " + user.getMessage());
    } else {
        System.out.println("    " + user.getName() + " has no messages");
    }
}


private static void pause() {
    System.out.print("\n...press enter...");
    KBD.nextLine();
}
}

还有我的(凌乱的未完成的)代码:

public class MyBookAccount {

public final int MAX_CHAR = 20;
public final int ID;
public static int nextId = 1;
private String name;
private String location;
private Boolean loggedIn;
private String wallPost = "(none)";
private String latestMessage = "(none)";
private MyBookAccount friend = null;
private static int numberOfAccounts = 0;

MyBookAccount(String n, String l, Boolean i) {
    name = n;
    location = l;
    loggedIn = i;
    ID = nextId;
    nextId++;
    numberOfAccounts++;
}

MyBookAccount(String n, Boolean i) {
    name = n;
    location = "Halifax";
    loggedIn = i;
    ID = nextId;
    nextId++;
    numberOfAccounts++;
}

MyBookAccount(String n) {
    name = n;
    location = "Halifax";
    loggedIn = false;
    ID = nextId;
    nextId++;
    numberOfAccounts++;
}

public static int getNumAccounts() {
    return numberOfAccounts;
}

public void setLoggedIn(boolean log) {
    loggedIn = !log;
}

boolean isLoggedIn() {
    return loggedIn;
}

public void setWallPost(String newPost) {
    if (newPost.length() > MAX_CHAR) {
        System.out.println("Cannot update wall post for " + name
                + ". Post must be 20 characters or less.");
    } else {
        wallPost = newPost;
    }

}

public String getWallPost() {
    return wallPost;
}

public String getMessage() {
    return this.latestMessage;
}

public void sendMessage(MyBookAccount to, String message) {
    friend = to;
    if (to.loggedIn != true) {
        System.out.println("Could not post message from " + name
                + ". " + to.name + " is not logged in!");
        latestMessage = "(none)";
    } else if (to.loggedIn == true) {
        latestMessage = message;
    }
}

public MyBookAccount getFriend() {
    return friend;
}

public void setName(String n) {
    name = n;
}

public String getName() {
    return name;
}

public void setLocation(String location) {
    this.location = location;
}

public String getLocation() {
    return location;
}

@Override
public String toString() {
    if (friend == null) {
        return "MyBookAccount #" + ID + "{\n    "
                + name + " in " + location + "\n    "
                + "About me: " + wallPost + "\n    "
                + "Logged In:" + loggedIn + "\n    ";

    } else {
        return "MyBookAccount #" + ID + "{\n    "
                + name + " in " + location + "\n    "
                + "About me: " + wallPost + "\n    "
                + "Logged In:" + loggedIn + "\n    "
                + "Message from " + friend.name + ": "
                + latestMessage + ".\n";
    }

}
}

我就是想不通一件事。

在消息部分,我混淆了消息来源和消息来源。 例如;应该说

Sending messages:
Could not post message from Leonard. Penny is not logged in!
    Sheldon's message from Amy is Neuroscience is a real science.
    Penny has no messages
    Amy's message from Penny is What a nice picture.
    Leonard has no messages

我得到:

Sending messages:
Could not post message from Leonard. Penny is not logged in!
    Sheldon has no messages
    Penny's message from Amy is What a nice picture.
    Amy's message from Sheldon is Neuroscience is a real science.
    Leonard has no messages

关于如何解决这个问题有什么想法吗? 谢谢捆绑。

最佳答案

我不想在这里调试您的代码,但让我对此发表评论:

public void sendMessage(MyBookAccount to, String message) {
    friend = to; 
    if (to.loggedIn != true) {
        System.out.println("Could not post message from " + name
                + ". " + to.name + " is not logged in!");
        latestMessage = "(none)";
    } else if (to.loggedIn == true) {
        latestMessage = message;
    }
}

这段代码有味道,因为它不会发送任何消息,而只是改变这个(发送者)对象的状态(friend = to,latestMessage = ...)。另外,它会检查接收者的状况,而消息应该只发送一条消息并对任何不良结果使用react。而是想象这样的事情:

class MyBookAccount {
    //....
    public void sendMessage(MyBookAccount receiver, String message) {
       try{
         receiver.accept(this, message);
       }catch(MessageRejectedException e){
         //maybe put in queue to try again later, or log the date, time and reason of failure.
       }
    }
}

地点:

class MyBookAccount {
  private final List<String> receivedMessages = new ArrayList<>();
  ...
  public void accept(MyBookAccount sender, String message){
      if(!loggedIn){
        throw new MessageRejectedException("not online");
      }
      receivedMessages.add(message);
      //you can also have a list of Objects that are like 
      //class Message{String senderName; String message; Date reveived; /*...*/}
      //trigger UI update or fire property changed event that announces the list of messages has changed
  }

  public Optional<String> getLastMessage(){
     return receivedMessages.isEmpty() ? Optional.empty() 
             : Optional.of(receivedMessages.get(receivedMessages.size()-1));
  }

通过这种方式,消息的接收者可以完全控制接收消息所需的条件,或者想要保留多少消息,或者是否想要记录消息的日期(接收消息的时间)。发送者并不关心接收者是否只是一个代理,接收者本身或者必须满足什么条件才能发送消息,它只需要处理可能的错误条件(可能有很多) - 并且也可以自由地忽略或记录它们。

关于Java初学者的烦恼;从方法调用。希望是小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40810448/

相关文章:

java - 如何在Eclipse项目中导入javax.servlet API?

java - 如何在 OpenGL 中围绕 Z 轴中心旋转对象?

c++ - 嵌套类是否可以访问其所有者的私有(private)变量?

c++ - 为什么以及何时执行重载构造函数?

ruby - Ruby 中的 CSV 导入 RSpec 错误

Java:将用户输入的变量从一种方法调用到另一种方法

java - 我想在非静态类中使用静态随机数。 ( java )

java - Java 中的优先级

javascript - 在 Ajax 中传递 URL 变量

c - 平均值计算器 - 为什么嵌套在 while 循环中的 "var += var;"不起作用?