在Java中遇到Get和set方法的问题

时间:2014-12-01 19:33:19

标签: java arrays getter-setter

我遇到了来自数组的get方法的问题。

public class Person 
{



    private String navn; 
    private int personNummer;
    private int alder;

    public Person (String navn, int personNummer, int alder)
    {
        this.navn = navn;
        this.personNummer = personNummer;
        this.alder = alder;

        }
       public static String getName(Person a){
            return a.navn;        


       }  
    }


    public class Kunderegister {
        private Scanner input;
        private Person [] brukere;
    int i = 0;

    public Kunderegister () 
    {
        input = new Scanner(System.in);
        brukere = new Person [20];
    }
    public void leggTilBruker()
    {
     System.out.println("give the name"); 
        System.out.println("Give name");
        String name = input.nextLine();
        System.out.println("Give age");
        int age = input.nextInt();
        System.out.println("Give number");
        int number = input.nextInt();
        Person a = new Person(name,number,age);
        brukere[i]=a;
        i++;

    }
    public void visPersonListe()
    {
      for (int j = 0; j > 20; j++){
            System.out.println(Person.getName(brukere[0]));

        }
    }

因此,当我运行此代码时,它没有构建错误,但它不会打印出客户的名称。知道我做错了什么吗?

2 个答案:

答案 0 :(得分:4)

你的循环条件是

for (int j = 0; j > 20; j++){
    System.out.println(Person.getName(brukere[0]));

将循环中的j > 20更改为j < 20条件,并将brukere[0]的索引更改为brukere[j]

另外

  

您不需要将Person对象传递给getter,即信息   你需要的已经存在了。只需返回Person.getName(brukere [j]);

将其更改为以下或类似内容: -

for (int j = 0; j < 20; j++){
    System.out.println(Person.getName(brukere[j]));

答案 1 :(得分:1)

吸气剂不应该是静态的。我做了一些修改。这应该有效:

public class Person  
{ 
    private String navn; 
    private int personNummer;
    private int alder;

    public Person (String navn, int personNummer, int alder)
    { 
        this.navn = navn;
        this.personNummer = personNummer;
        this.alder = alder;
    } 

    public String getName() {
        return this.navn;        
    }   
}

public class Kunderegister { 
    private Scanner input;
    private Person [] brukere;
    int i = 0;

    public Kunderegister ()  
    { 
        input = new Scanner(System.in);
        brukere = new Person [20];
    } 

    public void leggTilBruker() 
    { 
        System.out.println("give the name"); 
        System.out.println("Give name");
        String name = input.nextLine();
        System.out.println("Give age");
        int age = input.nextInt();
        System.out.println("Give number");
        int number = input.nextInt();
        Person a = new Person(name,number,age);
        brukere[i]=a;
        i++;
    } 

    public void visPersonListe() 
    { 
        for (int j = 0; j < brukere.length; j++) {
            System.out.println(brukere[j].getName());
        } 
    }