0

如果我做错了什么,第一次用户非常抱歉。

我必须编写一个程序,根据用户输入的内容对数组进行排序。从文件中读取数据。该文件Bank.txt包含10,000 个帐户,其中一些是空帐户,默认值为0000, ,00.00.

目前的输出是:

ID#1234 joe     $436.0
ID#3620 kim     $600.0
ID#4563 Jimmy   $1653.0
ID#4571 Billy   $72.0
ID#5930 Brian   $962.0
ID#6766 Jen     $215.0
ID#7092 Adam    $8794.0

它看起来只是按 排序,ID因为这是它在 txt 文档中的写入方式。我不知道从哪里开始。我需要根据用户输入的内容进行ID排序。我知道有,但这在这里行不通(除非我想多了),因为它只会对该数组中的电流进行排序。再次感谢任何帮助。NameBalancearray.sort(array)id,name,balance

按名称排序应显示:

ID#7092 Adam    $8794.0
ID#4571 Billy   $72.0
ID#5930 Brian   $962.0
ID#6766 Jen     $215.0
ID#4563 Jimmy   $1653.0
ID#1234 joe     $436.0
ID#3620 kim     $600.0

按余额排序:

ID#4571 Billy   $72.0 <br>
ID#6766 Jen     $215.0 <br>
ID#1234 joe     $436.0 <br>
ID#3620 kim     $600.0 <br>
ID#5930 Brian   $962.0 <br>
ID#4563 Jimmy   $1653.0 <br>
ID#7092 Adam    $8794.0 <br>

程序代码:

import static java.nio.file.AccessMode.*;
import java.nio.file.*;
import java.io.*;
import java.util.Arrays;

public class ReadBankSequentially
{
    public static void main(String[] args)
    {
        Path file = Paths.get("Bank.txt");
        String[] array = new String[3];
        String s = "";
        String delimiter = ",";
        int id;
        String stringId;
        String name;
        double balance;

        try
        {

            InputStream input = new BufferedInputStream(Files.newInputStream(file));
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            System.out.println();
            s = reader.readLine();
            while(s != null)
            {
                array = s.split(delimiter);
                stringId = array[0];
                id = Integer.parseInt(array[0]);
                if(id != 0)
                {
                    name = array[1];
                    balance = Double.parseDouble(array[2]);
                    System.out.println("ID#" + stringId + " " + name + " $" + balance); 

                }
                s = reader.readLine();
            }
            reader.close();
        }
        catch(Exception e)
        {
            System.out.println("Message: " + e);
        }
    }
}
4

4 回答 4

2

我会创建一个Customer DTO

public class Customer {
  protected int _id;
  protected String _name;
  protected float _balance;

  public Customer() {
    init(0, "New Customer", 0.00f);
  }

  public Customer(int id, String name, float balance) {
    init(id, name, balance);
  }

  private void init(int id, String name, float balance) {
    id(id).name(name).balance(balance);
  }

  public int id() {
    return this._id;
  }
  public Customer id(int id) {
    this._id = id;
    return this;
  }

  public String name() {
    return this._name;
  }
  public Customer name(String name) {
    this._name = name;
    return this;
  }

  public float balance() {
    return this._balance;
  }
  public Customer balance(float balance) {
    this._balance = balance;
    return this;
  }

  public String toString() {
    return String.format("#%d: %-5s - $%07.2f", id(), name(), balance());
  }
}

接下来,我将创建一个实用程序类来读取文件并生成客户:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Utils {  
  public static List<Customer> getCustomers(String filename, String delimiters) {
    List<Customer> customers = new ArrayList<Customer>();
    Customer customer = null;
    File file = new File(filename);
    Scanner scanner = null;
    try {
      scanner = new Scanner(file);
      while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if ((customer = createCustomer(line, delimiters)) != null)
          customers.add(customer);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } finally {
      scanner.close();
    }

    return customers;
  }

  public static Customer createCustomer(String line, String delimiter) {
    String[] arr = line.split(delimiter);
    if (arr.length < 3)
      return null;
    int id = Integer.parseInt(arr[0].trim());
    String name = arr[1].trim();
    float balance = Float.parseFloat(arr[2].trim());
    return new Customer(id, name, balance);
  }
}

最后我会创建我的Bank类来存储Customers 并可以将它们排序/打印出来。

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static bank.Utils.getCustomers;

public class Bank {
  protected List<Customer> customers;

  public enum Sort {
    ID, NAME, BALANCE
  }

  public Bank() {
    String filename = "bank/Bank.txt";
    String delimiters = "[,]";
    customers = getCustomers(filename, delimiters);

    printCustomers(Sort.ID, false);
    printCustomers(Sort.ID, true);
    printCustomers(Sort.NAME, false);
    printCustomers(Sort.NAME, true);
    printCustomers(Sort.BALANCE, false);
    printCustomers(Sort.BALANCE, true);
  }

  public void sortId(boolean descending) {
    final int d = descending ? -1 : 1;
    Comparator<Customer> comparator = new Comparator<Customer>() {
      public int compare(Customer c1, Customer c2) {
        return (c1.id() > c2.id() ? 1 :
               c1.id() == c2.id() ? 0 : -1) * d;
      }
    };
    Collections.sort(customers, comparator);
  }

  public void sortName(boolean descending) {
    final int d = descending ? -1 : 1;
    Comparator<Customer> comparator = new Comparator<Customer>() {
      public int compare(Customer c1, Customer c2) {
        return (c1.name().compareTo(c2.name())) * d;
      }
    };
    Collections.sort(customers, comparator);
  }

  public void sortBalance(boolean descending) {
    final int d = descending ? -1 : 1;
    Comparator<Customer> comparator = new Comparator<Customer>() {
      public int compare(Customer c1, Customer c2) {
        return (c1.balance() > c2.balance() ? 1 :
               c1.balance() == c2.balance() ? 0 : -1) * d;
      }
    };
    Collections.sort(customers, comparator);
  }

  public void printCustomers(Sort sortBy, boolean descending) {
    String header = "";
    String desc = descending ? "descending" : "ascending";
    switch (sortBy) {
      case NAME:
        header = "Sorting by Name";
        sortName(descending);
        break;
      case BALANCE:
        header = "Sorting by Balance";
        sortBalance(descending);
        break;
      case ID:
        header = "Sorting by Id";
      default:
        sortId(descending);
        break;
    }
    System.out.printf("### %s %s ###\n", header, desc);
    for (Customer c : customers)
      System.out.println(c);
    System.out.println();
  }

  public static void main(String[] args) {
    new Bank();
  }
}

输入文件

1234,Joe,436.00
3620,Kim,600.00
4563,Jimmy,1653.00
4571,Billy,72.00
5930,Brian,962.00
6766,Jen,215.00
7092,Adam,8794.00

输出

### Sorting by Id ascending ###
#1234: Joe   - $0436.00
#3620: Kim   - $0600.00
#4563: Jimmy - $1653.00
#4571: Billy - $0072.00
#5930: Brian - $0962.00
#6766: Jen   - $0215.00
#7092: Adam  - $8794.00

### Sorting by Id descending ###
#7092: Adam  - $8794.00
#6766: Jen   - $0215.00
#5930: Brian - $0962.00
#4571: Billy - $0072.00
#4563: Jimmy - $1653.00
#3620: Kim   - $0600.00
#1234: Joe   - $0436.00

### Sorting by Name ascending ###
#7092: Adam  - $8794.00
#4571: Billy - $0072.00
#5930: Brian - $0962.00
#6766: Jen   - $0215.00
#4563: Jimmy - $1653.00
#1234: Joe   - $0436.00
#3620: Kim   - $0600.00

### Sorting by Name descending ###
#3620: Kim   - $0600.00
#1234: Joe   - $0436.00
#4563: Jimmy - $1653.00
#6766: Jen   - $0215.00
#5930: Brian - $0962.00
#4571: Billy - $0072.00
#7092: Adam  - $8794.00

### Sorting by Balance ascending ###
#4571: Billy - $0072.00
#6766: Jen   - $0215.00
#1234: Joe   - $0436.00
#3620: Kim   - $0600.00
#5930: Brian - $0962.00
#4563: Jimmy - $1653.00
#7092: Adam  - $8794.00

### Sorting by Balance descending ###
#7092: Adam  - $8794.00
#4563: Jimmy - $1653.00
#5930: Brian - $0962.00
#3620: Kim   - $0600.00
#1234: Joe   - $0436.00
#6766: Jen   - $0215.00
#4571: Billy - $0072.00
于 2013-04-20T22:14:52.233 回答
0

创建一个“AccountEntry”类:

class AccountEntry {
  String id;
  String name;
  int balance;
}

创建三个“比较器”:

class IdComparator implements java.lang.Comparator {
  public int compare(Object o1, Object o2) {
    AccountEntry a1 = (AccountEntry) o1;
    AccountEntry a2 = (AccountEntry) o2;
    return a1.id.compareTo(a2.id);
  }
}

class NameComparator implements java.lang.Comparator {
  public int compare(Object o1, Object o2) {
    AccountEntry a1 = (AccountEntry) o1;
    AccountEntry a2 = (AccountEntry) o2;
    return a1.name.compareTo(a2.name);
  }
}

class BalanceComparator implements java.lang.Comparator {
  public int compare(Object o1, Object o2) {
    AccountEntry a1 = (AccountEntry) o1;
    AccountEntry a2 = (AccountEntry) o2;
    if (a1.balance > a2.balance)
      return 1;
    if (a1.balance == a2.balance)
      return 0;
    return -1;
  }
}

排序使用

Collections.sort(List, comparator)
于 2013-04-20T22:16:14.213 回答
0

首先,您需要将数据保存在一个结构(类)中,该结构(类)将包含足够的数据来支持来自文件的传入数据。让我们称之为BankAccount类:

public class BankAccount {
    //NOTE: you can change the type of the elements used here, like double per BigDecimal
    private long id;
    private String owner;
    private double amount;
    //class constructors...
    //getters and setters...
}

其次,您需要将这些对象存储在可以像数组或List. 我会推荐一个List<BankAccount>

public class Bank {
    private List<BankAccount> accounts = new ArrayList<BankAccount>();
    //getters and setters...
}

第三,您必须对数组进行排序。如果您处于学习阶段,则需要实现一种算法来对数组进行排序。如果您对 Java 有一定的经验,您可以使用Collections#sort(List, Comparator)并发送您的List<BankAccount> accounts作为第一个参数和Comparator<BankAccount>作为第二个参数。我将定义一个比较器示例,以根据帐户所有者名称对帐户进行排序(使用匿名类):

public void sortByOwner() {
    Comparator<BankAccount> comparator = new Comparator<BankAccount>() {
        public int compare(BankAccount account1, BankAccount account2) {
            return account1.getOwner().compareTo(account2.getOwner());
        }
    };
    Collections.sort(accounts, comparator);
}
于 2013-04-20T22:16:49.607 回答
0

为简单起见,定义一个User类型:

class User
{
    public int id;
    public String name;
    public double balance;

    public User(int id, int name, int balance)
    {
        this.id = id;
        this.name = name;
        this.balance = balance;
    }
}

然后为它定义Comparator类型(因为你可以有不同的比较规则):

class UserComparatorByBalance implements Comparator<User>
{
    public int compare(User a, User b)
    {
        if (a.balance > b.balance) return 1; // or -1
        if (a.balance < b.balance) return -1; // or 1
        return 0;
    }
}

然后,填充一个集合(列表):

        ArrayList<User> users = new ArrayList<User>();
        s = reader.readLine();
        while(s != null)
        {
            array = s.split(delimiter);
            stringId = array[0];
            id = Integer.parseInt(array[0]);
            if(id != 0)
            {
                name = array[1];
                balance = Double.parseDouble(array[2]);
                System.out.println("ID#" + stringId + " " + name + " $" + balance); 
                User user = new User(id, name, balance);
                users.add(user);
            }
            s = reader.readLine();
        }
        reader.close();

最后,排序:

Collections.sort(users, new UserComparatorByBalance());
于 2013-04-20T22:17:28.980 回答