Algs4-1.3.17从文件中读取信息生成Transaction对象数组

 1.3.17为Transaction类完成练习1.3.16。
 答:public static Transaction[] readTransactions(String name)
图片
import java.util.Date;
public class Transaction
{
    private final String myWho;
    private final SmartDate myWhen;
    private final double myAmount;
   
    public Transaction(String who,SmartDate when,double amount)
    {
        myWho=who;
        myWhen=when;
        myAmount=amount;
      }
   
    public Transaction(String transaction)
    {
        String[] words=transaction.split(" ");
        myWho=words[0];
        myWhen=new SmartDate(words[1]);
        myAmount=Double.parseDouble(words[2]);
    }
   
    public String who()
    {
        return myWho;
    }
   
    public SmartDate when()
    {
        return myWhen;
    }
   
    public double amount()
    {
        return myAmount;
    }
   
    public boolean equals(Object x)
    {
        if(this==x) return true;
        if(x==null) return false;
        if(this.getClass()!=x.getClass())  return false;
        Transaction that=(Transaction) x;
        if(!this.myWho.equals(that.who())) return false;
        if(!this.myWhen.equals(that.when())) return false;
        if(this.myAmount!=that.amount()) return false;
        return true;
    }
   
    public String toString()
    {
        return myWho+" " +myWhen.toString() +" " +myAmount;
    }
   
   public static Transaction[] readTransactions(String name)
    {
        In in=new In(name);
        Queue<String> q=new Queue<String>();
        while(!in.isEmpty())
            q.enqueue(in.readString());

        int N=q.size()/3;
        Transaction[] a=new Transaction[N];
        for(int i=0;i<N;i++)
           a[i]=new Transaction (q.dequeue()+" " + q.dequeue()+" "+q.dequeue());
           
        return a;
    }
       
    public static void main(String[] args)
    {
         Transaction[] b=Transaction.readTransactions(args[0]);
        for(int i=0;i<b.length;i++)
            StdOut.printf("%s\n",b[i].toString());
    }
}

posted @ 2018-10-25 14:09  修电脑的龙生  阅读(200)  评论(0编辑  收藏  举报