Okay, I'm still learning programming, and I have this assignment where I have to create a class Message, which 4 instance variables: sender, receiver, subject and body. I have to implement a constructor that takes four parameters and initializes the attributes accordingly.
I have to implement a method isValid() that returns true only if: the Message object on which the method is invoked has a non-empty sender and receiver, and at least one of the body or subject must be a non-empty string.
Along with a toString() method. I understand all this, and here is my code so far. I have no idea what I am doing wrong.
public class Message { String sender; String receiver; String subject; String body; public Message(String sender, String receiver, String subject, String body) { this.sender = sender; this.receiver = receiver; this.subject = subject; this.body = body; } public Message() { this.sender = null; this.receiver = null; this.subject = null; this.body = null; } public static void main (String[] args) { Message trying = new Message(); trying.sender = "sendername"; trying.receiver = null; trying.subject = "Hi"; trying.body = null; System.out.println(trying); System.out.println(trying.isValid()); } public boolean isValid () { boolean flag = false; if (sender.length() > 0 && receiver.length() > 0) flag = true; if(subject.length() >0 || body.length()>0) flag = true; else flag = false; return flag; } public String toString() { return ("From: " + sender + "\n" + "To: " + receiver + "\n" + "Subject: " + subject + "\n" + "Body: " + body); } }
When I run this, I get a runtime exception (it compiles, but when I run) I get this:
Exception in thread "main" java.lang.NullPointerException
at Message.isValid(Message.java:40)
at Message.main(Message.java:33)