gpt4 book ai didi

Java打印数组列表

转载 作者:行者123 更新时间:2023-11-30 03:12:31 24 4
gpt4 key购买 nike

这是我的 2 个类(class),它们有效。我想将Member添加到LanArrayList中。我的问题是,我似乎无法打印出 LanArrayList 中设置的成员、名称和别名或只是名称。当我打印出来时:Member@1279d2f,有什么想法吗? :S

import java.util.ArrayList;

public class Lan
{

private ArrayList<Member> members;



public Lan()
{
members = new ArrayList<Member>();

}

public void addMember(Member newMember)
{
if(newMember.getBalance() >= 200)
{
this.members.add(newMember);
}
else
{
System.out.println("You dont have enough money to enter");
}

}
public void printMembers(){

System.out.println("People attending");
for(Member member : members){

System.out.println(member);
}

}

}


public class Member
{

private String name;
private String alias;
private int balance;


public Member(String fullName, String nickname)
{
this.name = fullName;
this.alias = nickname;
this.balance = 0;
}
public void setBalance(int account)
{
if(account > 0)
{
balance = balance + account;
}
else
{
System.out.println("You have not entered a valid number");
}
}

public String getName()
{
return name;
}
public String getAlias()
{
return alias;
}

public int getBalance()
{
return balance;
}
}

最佳答案

您必须为您的 Member 类定义一个 toString() 方法:

public class Member { 

private String name;
private String alias;
private int balance;


public Member(String fullName, String nickname)
{
this.name = fullName;
this.alias = nickname;
this.balance = 0;
}
public void setBalance(int account)
{
if(account > 0)
{
balance = balance + account;
}
else
{
System.out.println("You have not entered a valid number");
}
}

public String getName()
{
return name;
}
public String getAlias()
{
return alias;
}

public int getBalance()
{
return balance;
}

@Override
public String toString() {
return this.name + "\t" + this.balance;
}

}

如果您的自定义类没有 toString() 方法,您将打印它在内存中的位置。如果您还想在成员(member)中打印其他信息,请修改我为您提供的方法。

关于Java打印数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33330399/

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