gpt4 book ai didi

java - Java 中的 Get 和 set 方法出现问题

转载 作者:行者123 更新时间:2023-12-01 17:01:47 25 4
gpt4 key购买 nike

我在从数组获取方法时遇到问题。

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

}
}

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

最佳答案

你的循环条件是

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

更改 j > 20j < 20循环中的条件以及 brukere[0] 的索引至brukere[j] .

还有

You don't need to pass Person object to the getter, the information you need is already there. Simply return Person.getName(brukere[j]);

将其更改如下或类似的内容:-

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

关于java - Java 中的 Get 和 set 方法出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27235811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com