-2

我的程序是一个涉及对象使用的简单程序。没有错误,唯一的问题是我的程序打印出垃圾。在它询问用户姓名、年龄和性别之后。

下面是两组程序。第一个是人的物体或骨架。第二个是询问用户名年龄性别并打印出来的打印。

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);
}

我们正在学习基本对象,例如我们只学习了私有变量、构造函数、访问器、修改器和辅助方法。

4

2 回答 2

2

在您的 toString() 中,您有两个错误。您需要使用+between gender"/n"\n如果您想要换行符,则需要使用。

public String toString () {
    return "Name " + name + "\n" +
           "Age" + age + "\n" +
           "Gender: " + gender + "\n" +
           "Personality " + personality + "\n" +
           "Appearance " + appearance + "\n";
}
于 2016-04-19T02:44:30.810 回答
0

如果问题是未正确打印性别,则问题出在您的构造函数中。您正在传递gend,但没有保存它。gender相反,您使用成员变量覆盖参数:

public Person(String nm, int ag,String gend)
{
    name=nm;
    age=ag;
    gend=gender;

你自找的:

    gender = gend;
于 2016-04-19T02:43:44.313 回答