两个人的对象

时间:2012-02-22 07:37:30

标签: java

import cs1.Keyboard;
import java.util.Scanner;
class Person 
{
    private String name;
    private String persnr;
    private String adress;
    private int age;

    public Person(String _name, String _persnr, String _adress, int _age) 
    {
        name = name;
        persnr = persnr;
        adress = adress;
        age = age;
    }

    public void byterNamn(String _name)
    {
        name = _name;
    }

    public void byterAdress(String _adress)
    {
        adress = _adress;
    }

    public void fyllerAr()
    {
        age = age + 1;
    }

    public String hamtaNamn()
    {
        return name;
    }

    public String hamtaPersonnmmer()
    {
        return persnr;
    }

    public String hamtaAdress()
    {
        return adress;
    }

    public int hamtaAlder()
    {
        return age;
    }

    public String toString()
    {
    String _toString;
    _toString = "Namn: " + name + "\nÅlder: " + age;
    _toString = _toString +  "\nPersonnummer: " + persnr + "\nAdress: " + adress;
    return _toString;
    }

     public p1()
     {
       System.out.print("namn: ");
        name = Keyboard.readString();    

        System.out.print( "adress: " );
        String adress = Keyboard.readString();

        System.out.print( "ålder: " );
        Integer age = new Integer(); 
        age.parseInt(Keyboard.readint());

        System.out.print( "personnummer: " );
        String persnr = Keyboard.readString();

     }
     public p2()
     {
       System.out.print("namn: ");
        name = Keyboard.readString();    

        System.out.print( "adress: " );
        String adress = Keyboard.readString();

        System.out.print( "ålder: " );
        Integer age = new Integer(); 
        age.parseInt(Keyboard.readint());

        System.out.print( "personnummer: " );
        String persnr = Keyboard.readString();
     }

    public static void main(String[] args) 
    {
        String name = Keyboard.readString();
        String persnr = Keyboard.readString();
        String adress = Keyboard.readString();
        int age = Keyboard.readint(); 
        Person p1 = new Person(name, age, adress, personnummer);

        String name = Keyboard.readString();
        String persnr = Keyboard.readString();
        String adress = Keyboard.readString();
        int age = Keyboard.readint(); 
        Person p2 = new Person(name, age, adress, personnummer);

    }
}

您好。 我试着这样做是2个人。在哪里输入两个人的年龄,姓名,地址,然后在程序运行后输入所需内容后打印出来。我想知道如何返回公共p1()和公共p2(),所以我可以做到这一点。或者这是一种更简单的方法吗?

1 个答案:

答案 0 :(得分:0)

此代码无法编译。 public p1()public p2()不是有效的方法声明。您必须至少在public之后和方法名称之前添加方法返回类型,例如:

public Person p1()

然后我想你要做的是从这两种方法中的每一种返回一个Person对象。在方法内部,您必须创建一个新的Person对象,然后从方法中返回它:

return new Person(name, persnr, adress, age);

请参阅Oracle Java教程中的Defining MethodsReturning a Value from a Method