我的程序是一个涉及对象使用的简单程序。没有错误,唯一的问题是我的程序打印出垃圾。在它询问用户姓名、年龄和性别之后。
下面是两组程序。第一个是人的物体或骨架。第二个是询问用户名年龄性别并打印出来的打印。
public class Person
{
private String name;
private int age,personality,appearance;
private String gender;
//constructor method. only use it 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 like print but not really 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 is your name");
name =input.nextLine();
System.out.println("What your age?");
age=input.nextInt();
input.nextLine();
System.out.println ("What is your gender");
gender =input.nextLine();
person=new Person (name,age,gender);
System.out.println(person);
}
我们正在学习基本对象,例如我们只学习了私有变量、构造函数、访问器、修改器和辅助方法。