Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将对象放入链接列表中?_Java_Class_Linked List - Fatal编程技术网

Java 如何将对象放入链接列表中?

Java 如何将对象放入链接列表中?,java,class,linked-list,Java,Class,Linked List,我正在尝试做一个银行记录,并尝试使用链表。我创建了我的bank类,我试图把它作为一个对象放在我的主类中并打印输出。所以如果我输入詹姆斯作为名字,布莱克作为我的姓,200作为余额。它应该打印输出:FirstName:James,Lastname:Black,Balance:200。如果我再加上一个第一,最后,平衡。它应该用旧记录打印新记录 Example: First name Lastname Balance James Shown 4000

我正在尝试做一个银行记录,并尝试使用链表。我创建了我的bank类,我试图把它作为一个对象放在我的主类中并打印输出。所以如果我输入詹姆斯作为名字,布莱克作为我的姓,200作为余额。它应该打印输出:FirstName:James,Lastname:Black,Balance:200。如果我再加上一个第一,最后,平衡。它应该用旧记录打印新记录

Example:
First name      Lastname     Balance
James            Shown        4000
Kyle             Waffle       2000
银行类别:

public class Customer2 {
    String Firstname,Lastname;
    public int balance, amount;
    int total=0;
    int total2=0;
    Scanner input = new Scanner(System.in);

public Customer2(String n, String l, int b){
    Firstname=n;
    Lastname=l;
    balance=b;
}
    public void withdraw(int amount){
        total=balance-amount;
        balance=total;

    }
    public void deposit(int amount){
        total=balance+amount;
        balance=total;
    }
    public void display(){
        System.out.println("FirstName: "+" Lastname: "+" Balance");
        System.out.println(Firstname+"         "+Lastname+"      " +balance);
    }
主要类别:

LinkedList<Customer2> list = new LinkedList<Customer2>();
list.add("Bob");
list.getfirst("Lastname");
LinkedList=新建LinkedList();
列表。添加(“Bob”);
list.getfirst(“Lastname”);
要打印列表中的所有对象,请在新行中打印每个Customer2对象

for(Customer2 c : list){
   System.out.println(c);
}

如果您想将元素放入
链接列表
中,您需要使用方法
list.add(customer)
其中
customer
是class
Customer2
中的对象,您应该创建一个新的Customer2对象,然后将其添加到链接列表中

它看起来是这样的: 主要类别:

Customer2 customer = new Customer2("Bob", "Doe", 1000);
list.add(customer);
Bob现在将被添加到链接列表中

如果您想从链接列表中检索bob,您可以遍历列表,直到找到bob,然后调用该对象上的display

或者可以使用getFirst(如果bob是列表中的第一个)

看起来是这样的:

list.getFirst().display();
如果知道位置,可以使用链表类中的其他方法添加或获取。以下是一个链接:

另外,我认为这就是您希望display()方法的内容:

public void display(){
System.out.println("First Name: " + firstName + ", Last Name: " + lastName + ", Balance: " + balance);

您还应该使用小写字母来开始变量名,因为这是一种很好的命名约定。Firstname变成Firstname。

你的问题是什么?我如何将我的银行类作为对象放在链接列表中。你需要创建一个新的customer2对象并将其添加到链接列表中感谢这有助于降低成本,如果我将另一个人添加到列表中。它不会跳到一个新的行,你能举个例子吗?谢谢,这很有意义。我遇到的问题是,如果我将另一个人添加到列表中并打印出来。它不会像应该的那样跳过一行。
list.getFirst().display();
public void display(){
System.out.println("First Name: " + firstName + ", Last Name: " + lastName + ", Balance: " + balance);