Java中的对象正在打印出垃圾

时间:2016-04-19 02:30:11

标签: java object constructor helpermethods

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

下面是两套程序。第一个是人的对象或骨架。第二个是要求用户名年龄性别并打印出来的打印件。

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

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

2 个答案:

答案 0 :(得分:2)

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

public String toString () {
    return "Name " + name + "\n" +
           "Age" + age + "\n" +
           "Gender: " + gender + "\n" +
           "Personality " + personality + "\n" +
           "Appearance " + appearance + "\n";
}

答案 1 :(得分:0)

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

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

你想:

    gender = gend;