java - Why does this code not return a string? -
public string tostring() { system.out.println(lastname + ", " + firstname); system.out.println(phonenumber); if (relationship == 'f') system.out.println("friend"); else if (relationship == 'm') system.out.println("family member"); else if (relationship == 'b') system.out.println("buisness associate"); else system.out.println("not specified"); }
this not work because says code not homecoming string, , don't know why.
because you're not using return <variable> statement in code. printing in system.out stream is not same returning string.
instead printing desired content of string output, improve append of string , homecoming string client.
here's example:
public string tostring() { stringbuilder result = new stringbuilder(lastname) .append(", ") .append(firstname) .append('\n') .append(phonenumber); if (relationship == 'f') result.append(" friend"); else if (relationship == 'm') result.append(" family member"); else if (relationship == 'b') result.append(" business associate"); else result.append(" not specified"); homecoming result.tostring(); } also, seek tostring method returns way understand info stored in object. example:
public string tostring() { stringbuilder result = new stringbuilder("name: ") .append(lastname) .append(", ") .append(firstname) .append(". phone number: ") .append(phonenumber) .append(". relationship: "); if (relationship == 'f') result.append(" friend"); else if (relationship == 'm') result.append(" family member"); else if (relationship == 'b') result.append(" business associate"); else result.append(" not specified"); homecoming result.tostring(); } java
No comments:
Post a Comment