2016-03-12 36 views
-4

我正在尝试创建银行记录并尝试使用链接列表。我做了银行课程,我试图把它作为主要课程中的一个对象并打印输出。所以如果我输入詹姆斯作为名字,黑色作为我的姓氏,200作为平衡。它应该打印输出:名字:詹姆斯,姓:黑色,平衡: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); 
    } 

主类:在顾客2类

LinkedList<Customer2> list = new LinkedList<Customer2>(); 
list.add("Bob"); 
list.getfirst("Lastname"); 
+0

你的问题是什么? – ByeBye

+0

如何将我的银行类作为对象放入链接列表中? –

+0

您需要创建一个新的customer2对象并将其添加到您的链接列表 –

回答

0

您应该创建一个新的customer2对象,然后添加到您的链表

它应该是这样的: 主类:

Customer2 customer = new Customer2("Bob", "Doe", 1000); 
list.add(customer); 

鲍勃现在将被添加到链表。

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

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

,将是这样的:

list.getFirst().display(); 

有中,你可以使用链表类的其他方法如果你知道该位置,请添加或获取。这里是一个链接:http://www.tutorialspoint.com/java/java_linkedlist_class.htm

我也觉得这是你想要你的display()方法是什么:

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

,你也应该使用小写字母开始的变量名,因为它是良好的命名惯例又名。名字成为名字。

+0

谢谢,这很有道理。我遇到的问题是如果我将其他人添加到列表中并打印出来。它不会像它应该跳过一条线。 –

-1
LinkedList<Customer2> list = new LinkedList<Customer2>(); 
Customer2 c = new Customer2("firstName","lastName",1000); 
list.add(c); 
System.out.println(list); 

覆盖的toString():

@Override 
    public String toString(){ 
     return "FirstName: "+fristName+",lastName: "+lastName,+"balance" +balance; 
    } 

//toString() 
//returns string for the object 

,如果你希望把LinkedList<Customer2> list你需要使用方法list.add(customer)其中customerCustomer2类对象元素打印所有对象列表,每个顾客2物体在一个新行

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

谢谢帮助低 –

+0

所以,如果我将其他人添加到列表中。它不会跳到一个新行 –

0

+0

你可以做一个例子。 –

相关问题