user738647 user738647 - 5 months ago 12
Java Question

Where did I go wrong in this code?

A few of my classes aren't passing automated tests. Unfortunately, said tests do not provide any useful information about why they failed. Here is my code for a couple of the classes. I'd really appreciate it if you could tell me where I went wrong. The comments should explain what each method is supposed to do.

public class CellPhone {
protected String ownerName;

public CellPhone(String owner) {
ownerName = owner;


}

public String receiveCall(CellPhone sender) {
// returns a String of the form:
// owner's name " is receiving a call from " sender's name
String receivingCall = ownerName + " is receiving a call from " + sender;

return receivingCall;
}

public String call(CellPhone receiver) {
// returns a String by using the receiver to invoke receiveCall
// while passing in the current phone
String invokingReceiveCall = receiver.receiveCall(receiver);

return invokingReceiveCall;

}
}





public class TextMessagingPhone extends CellPhone {
private int availMessages;

public TextMessagingPhone(String owner, int messageLimit) {
// invokes the superclass constructor
super(owner);
// sets the new instance variable
availMessages = messageLimit;
}

public TextMessagingPhone(String owner) {
// invokes the other constructor of this class with 15 as the message limit
this(owner, 15);
}

public String receiveText(TextMessagingPhone sender, String message) {
// decreases the number of messages available to send
availMessages--;

// returns a String of the form:
// owner's name " has received TEXT from " sender's name ":" message
String receivedText = ownerName + " has received TEXT from " + sender + ":" + message;

return receivedText;
}

public String sendText(TextMessagingPhone receiver, String message) {
// decreases the number of messages available to send
availMessages--;

// returns a String by using the receiver to invoke receiveText
// while passing in the current phone and the message
String invokingReceiveText = receiver.receiveText(receiver, message);

return invokingReceiveText;
}
}

Ed. Ed.
Answer

When a phone makes a call, it passes the receiver as a parameter, so the receiver thinks it is receiving from itself. Also it never gets the name from the passed sender. Try:

public String receiveCall(CellPhone sender) {        
    // returns a String of the form:        
    // owner's name " is receiving a call from " sender's name        
    String receivingCall = ownerName + " is receiving a call from " + sender.getName();        
    return receivingCall;    
}

public String call(CellPhone receiver) {        
    // returns a String by using the receiver to invoke receiveCall        
    // while passing in the current phone        
    String invokingReceiveCall = receiver.receiveCall(this);        
    return invokingReceiveCall;    
}

public String getName() {
    return ownerName;
}