Objects in Java is printing out junk -
my program simple program involves use of objects. there no errors problem program printing out junk. after asked user name, age , , gender.
down below 2 sets of programs. first 1 object or skeleton of person. second 1 print asks user name age gender , prints out.
public class person { private string name; private int age,personality,appearance; private string gender; //constructor method. use once public person(string nm, int ag,string gend) { name=nm; age=ag; gend=gender; personality=1+(int)(math.random()*10); appearance=1+(int)(math.random()*10); } //accessor created public string getname() { return name; } public string getgend() { return gender; } public int getint() { return age; } //mutator method. when using "void" no return type public void setname (string nm) { name=nm; } public void setage (int ag) { age=ag; } public void setgender (string gend) { gender=gend; } //helper method (kind of print not printing public string tostring () { string orange =""; orange ="name "+name+"/n"; orange +="age"+age+"/n"; orange +="gender: "+gender"/n"; orange +="personality "+personality+"/n"; orange +="apperance "+appearance+"/n"; return orange; } }
2)
import java .util.scanner; public class persontester { public static void main (string []args){ // calling person person person; string name="", gender =""; int age =0; scanner input =new scanner(system.in); system.out.println ("what name"); name =input.nextline(); system.out.println("what age?"); age=input.nextint(); input.nextline(); system.out.println ("what gender"); gender =input.nextline(); person=new person (name,age,gender); system.out.println(person); }
we learning bout basic objects example learned private variables,constructor, accessor, mutator, , helper methods.
in tostring() have 2 errors. need use +
between gender"/n"
, need use \n
if want newline.
public string tostring () { return "name " + name + "\n" + "age" + age + "\n" + "gender: " + gender + "\n" + "personality " + personality + "\n" + "appearance " + appearance + "\n"; }
Comments
Post a Comment