2016-03-13 2 views
0

Я пытаюсь сделать банковскую запись, которая продолжает повторяться, пока пользователь не войдет в команду Q, чтобы выйти. Мой цикл while выглядит отлично, но он повторяется только два раза, а затем останавливается. Также я пытаюсь написать список, который упорядочивает имена в соответствии с фамилией. Я попробовал напечатать его по имени, но он не печатает в соответствии с фамилией.Как сортировать имена в связанном списке?

Мой главный код класса:

public static void main(String args[]){  
    LinkedList<Customer2> bankRecords = new LinkedList<>(); 
    Scanner input=new Scanner(System.in); 
    System.out.println("Enter Command"); 
    String x=input.nextLine(); 


    while(true){ 
     if(x.equals("a")){ 
      if(bankRecords.isEmpty()){ 
       System.out.println("Records are empty"); 
       System.out.println("Enter a command"); 
       x=input.nextLine(); 

      }else { 
       printList(bankRecords); 

       System.out.println("a Show all records"); 
       System.out.println("r Remove the current record"); 
       System.out.println("f Change the first name in the current record"); 
       System.out.println("l Change the last name in the current record"); 
       System.out.println("n Add a new record"); 
       System.out.println("d Add a deposit to the current record"); 
       System.out.println("w Make a withdrawal from the current record"); 
       System.out.println("s Select a record from the record list to become the current record"); 
       System.out.println("Enter a command"); 
      } 
     } 

     if(x.equals("r")){ 
      bankRecords.removeLast(); 
      System.out.println("a Show all records"); 
      System.out.println("r Remove the current record"); 
      System.out.println("f Change the first name in the current record"); 
      System.out.println("l Change the last name in the current record"); 
      System.out.println("n Add a new record"); 
      System.out.println("d Add a deposit to the current record"); 
      System.out.println("w Make a withdrawal from the current record"); 
      System.out.println("s Select a record from the record list to become the current record"); 
      System.out.println("Enter a command"); 
      x=input.nextLine(); 
     } 
     if (x.equals("f")) { 
      Customer2 currentRecord = bankRecords.getLast(); 
      System.out.print("Enter Firstname: "); 
      String fname=input.nextLine(); 
      currentRecord.setFirstName(fname); 
      currentRecord.menu(); 
      System.out.println("Enter a command"); 
      x=input.nextLine(); 

     } 
     if (x.equals("l")) { 
      Customer2 currentRecord = bankRecords.getLast(); 
      System.out.print("Enter Last Name: "); 
      String lname=input.nextLine(); 
      currentRecord.setLastName(lname); 
      currentRecord.menu(); 
      System.out.println("Enter a command"); 
      x=input.nextLine(); 
     } 
     if(x.equals("d")){ 
      Customer2 currentRecord = bankRecords.getLast(); 
      System.out.print("Enter deposited amount"); 
      int deposit=input.nextInt(); 
      currentRecord.deposit(deposit); 
      currentRecord.menu(); 
      System.out.println("Enter a command"); 
      x=input.nextLine(); 

     } 
     if(x.equals("w")){ 
      Customer2 currentRecord = bankRecords.getLast(); 
      System.out.print("Enter Withdrawn amount"); 
      int withdraw=input.nextInt(); 
      currentRecord.withdraw(withdraw); 
      currentRecord.menu(); 
      System.out.println("Enter a command"); 
      x=input.nextLine(); 

     } 

     if(x.equals("n")){ 
      System.out.print("Enter first name: "); 
      String name=input.nextLine(); 
      System.out.println("Enter Last name"); 
      String lname=input.nextLine(); 
      System.out.print("Enter Balance:"); 
      int balance=input.nextInt(); 
      bankRecords.add(new Customer2(name, lname, balance)); 
      System.out.println("a Show all records"); 
      System.out.println("r Remove the current record"); 
      System.out.println("f Change the first name in the current record"); 
      System.out.println("l Change the last name in the current record"); 
      System.out.println("n Add a new record"); 
      System.out.println("d Add a deposit to the current record"); 
      System.out.println("w Make a withdrawal from the current record"); 
      System.out.println("s Select a record from the record list to become the current record"); 
      System.out.println("Enter a command"); 
      x=input.nextLine(); 

     } 
     if(x.equals("q")){ 
      return; 
     } 
     if(x.equals("s")){ 
      System.out.println("Enter first name"); 
      String fname=input.nextLine(); 
      for(int i=0;i<bankRecords.size();i++){ 
       if(bankRecords.contains(fname)){ 
        Customer2 cur=bankRecords.getLast(); 
       }}}}} 
public static void printList(LinkedList<Customer2> list) { 

    for (Customer2 data : list) { 

     System.out.println(data.getFirstName()+"\t"+data.getLastName()+"\t"+data.getAccountBalance()); 

    } 

} 

Мой второй класс:

public class Customer2 { 
    private String firstName; 
    private String lastName; 
    private int accountBalance; 
    public int total=0; 
    public Customer2(String fName, String lName, int balance){ 
     firstName = fName; 
     lastName = lName; 
     accountBalance = balance; 
    } 
    public void setFirstName(String newFirstName){ 
     firstName = newFirstName; 
     } 
     public void setLastName(String newLastName){ 
     lastName = newLastName; 
     } 
    public String getFirstName() { 

    return firstName; 

    } 

    public String getLastName() { 

    return lastName; 

    } 



    public double getAccountBalance() { 

    return accountBalance; 

    } 
    public void withdraw(int amount){ 
     total=accountBalance-amount; 
     accountBalance=total; 

    } 
    public void deposit(int amount){ 
     total=accountBalance+amount; 
     accountBalance=total; 
    } 



    public void menu(){ 

      System.out.println("a Show all records"); 
      System.out.println("r Remove the current record"); 
      System.out.println("f Change the first name in the current record"); 
      System.out.println("l Change the last name in the current record"); 
      System.out.println("n Add a new record"); 
      System.out.println("d Add a deposit to the current record"); 
      System.out.println("w Make a withdrawal from the current record"); 
      System.out.println("s Select a record from the record list to become the current record"); 
     } 
    } 
+0

* «Я пробовал печатать его по фамилии» * Где? – Radiodef

+0

Я думал, что он напечатает его в соответствии с последним – EazyProgramer

+0

Не могли бы вы отправить сообщение [MCVE] (http://www.stackoverflow.com/help/mcve) –

ответ

0

Ваша первая часть очень неаккуратно и трудно понять. Он даже не работает в течение двух циклов, мой случай для конкретного случая он побежал к вашему компьютеру. Если вы можете очистить код и сделать его понятным, тогда его можно будет ответить. Для второй части вам нужен отсортированный список на основе lastname. Для этого вам необходимо выполнить сравнение со своим классом Customer2.

public class Customer2 implements Comparable<Customer2>{ 
    private String firstName; 
    private String lastName; 
    private int accountBalance; 
    public int total=0; 
    public Customer2(String fName, String lName, int balance){ 
     firstName = fName; 
     lastName = lName; 
     accountBalance = balance; 
    } 
    public void setFirstName(String newFirstName){ 
     firstName = newFirstName; 
     } 
     public void setLastName(String newLastName){ 
     lastName = newLastName; 
     } 
    public String getFirstName() { 

    return firstName; 

    } 

    public String getLastName() { 

    return lastName; 

    } 



    public double getAccountBalance() { 

    return accountBalance; 

    } 
    public void withdraw(int amount){ 
     total=accountBalance-amount; 
     accountBalance=total; 

    } 
    public void deposit(int amount){ 
     total=accountBalance+amount; 
     accountBalance=total; 
    } 



    public void menu(){ 

      System.out.println("a Show all records"); 
      System.out.println("r Remove the current record"); 
      System.out.println("f Change the first name in the current record"); 
      System.out.println("l Change the last name in the current record"); 
      System.out.println("n Add a new record"); 
      System.out.println("d Add a deposit to the current record"); 
      System.out.println("w Make a withdrawal from the current record"); 
      System.out.println("s Select a record from the record list to become the current record"); 
     } 

    @Override 
    public int compareTo(Customer2 o) { 
     // TODO Auto-generated method stub 
     return o.lastName.compareTo(lastName); 

    } 
    } 

Тогда в вашем основном классе вы можете отсортировать список с помощью коллекции. Я также приложил измененную часть здесь

public static void printList(LinkedList<Customer2> list) { 

    Collections.sort(list); 
    System.out.println(list); 

} 
+0

Я не хочу использовать коллекцию. Можно ли обойтись без него. Также мой цикл while не работает, хотя я не вижу ничего неправильного в ti. – EazyProgramer

+0

Если вы хотите использовать свой собственный алгоритм сортировки для сортировки, вы можете следовать этому руководству http://stackoverflow.com/questions/27774168/sorting-objects-in-an-arraylist-without-using-collections-sort – mahbubcsedu

Смежные вопросы