【问题标题】:How to perform arithmetic operation between the objects written in a file?如何在文件中写入的对象之间执行算术运算?
【发布时间】:2015-05-01 12:05:22
【问题描述】:

在我的程序中,用户输入值并将这些值存储在 arrayList 中。 ArryList 对象被写入文件。我已经使用 file-i/o、object-i/o 流在文件中写入和读取。现在我想在对象之间执行加法和减法 (int or double)。也就是说,从一个账户取款应该与另一个账户相加,并且它们的价值必须减去并加上特定账户的金额。最后,我希望必须更新该值,以便它可以打印出来并显示当前状态。我怎么能这样做?

这是主类:

public class BankApp_Assignment {

    //static int numOfAcc = 0;
    public static void main(String[] args) {
        System.out.println("WELCOME TO OUR BANK!\n\n");

        List<BankAccount> bankAccounts = new ArrayList<BankAccount>();
        List<BankAccount> bankAccounts2 = new ArrayList<BankAccount>();
        ReaderWriter rw=new ReaderWriter();


        while (true) {
            System.out.println("Choose your option:\n"
                    + "1. Create new account\n"
                    + "2. Deposit/withdraw\n"
                    + "3. View One account\n"
                    + "4. Deleting an account\n"
                    + "5. View all the accounts\n"
                    + "6. Return to menu\n");

            System.out.println("*************\n"
                    + "************");

            option1 = sc.nextInt();
            sc.nextLine();
            //switch-case starts
            switch (option1) {
                case 1:
                    //create account
                    BankAccount bankAcc = new BankAccount();
                    System.out.println("Enter Full Name:");
                    bankAcc.setName(sc.nextLine());
                    System.out.println("Choose an Account Number:");
                    bankAcc.setAccNum(sc.nextInt());
                    System.out.println("Choose the initial amount:");
                    bankAcc.setInitiateAmount(sc.nextDouble());
                    //adding those into the arrayList
                    bankAccounts.add(bankAcc);
                    rw.writeToFile(bankAccounts);

                    System.out.println("-------------\n"
                            + "-------------");
                    break;
                case 2:
                     bankAccounts2=(List<BankAccount>)rw.readFromFile();
                    //First displaying the current accouns info
                    System.out.println("Name \tAccount No \tInitial Amount");
                    for (BankAccount bankAccount : bankAccounts2) {

                        System.out.println(bankAccount);

                    }

                    System.out.println("\t\t.........\n"
                            + "\t\t.........");

                    System.out.println("To transfer money within the bank accounts enter 1\n"
                            + "To deposit/withdraw money in the same account enter 2");
                    option2 = sc.nextInt();
                    sc.nextLine();

                    //inner switch-case starts
                    switch (option2) {
                        case 1:
                            /*
                            BankAccount is the class for setter and getter
                             bankAccounts2 is the arrayList for reading objects from file
                            */
                            bankAccounts2 = (List<BankAccount>) rw.readFromFile();
                            BankAccount fromAcc = null;
                            BankAccount toAcc = null;
                            System.out.println("Enter the account number you want to withdraw from:");

                            withdraw_accNum = sc.nextInt();

                            System.out.println("Enter the amount you want to withdraw:");

                            withdraw_amount = sc.nextDouble();
                            System.out.println("Enter the account number you want to deposit to:");

                            deposit_accNum = sc.nextInt();//the deposit amount is alwyas the same as withdraw_amount

                            //find the matching acc number:withdraw_accNum
                            for (BankAccount listItemsFirst : bankAccounts2) {
                                //if the withdraw acc num matches with the given one
                                if (listItemsFirst.getAccNum() == withdraw_accNum) {
                                    //store it
                                    fromAcc = listItemsFirst;
                                    break;
                                }
                            }
                            //find the matching acc number:  deposit_accNum
                            for (BankAccount listItemsSec : bankAccounts2) {
                                //if the withdraw acc num matches with the given one
                                if (listItemsSec.getAccNum() == deposit_accNum) {
                                    //store it
                                    toAcc = listItemsSec;
                                    break;
                                }
                            }
                            //if the withdraw amount is bigger than the current balance
                            if (withdraw_amount > fromAcc.getInitialAmount()) {
                                System.out.println("Withdrawing Amount was bigger than the Initial amount.\nChoose the menu again. .");
                                break;
                            }
                            //subtracting and adding the withdrawn amount
                            fromAcc.setInitiateAmount(fromAcc.getInitialAmount() - withdraw_amount);
                            toAcc.setInitiateAmount(toAcc.getInitialAmount() + withdraw_amount);
                            System.out.println("DONE!\t print them out to see the current status.");
                            System.out.println("");

                            break;
                        case 2://deposit/withdraw money in the same accounts
                            bankAccounts2=(List<BankAccount>)rw.readFromFile();
                            BankAccount fromAcc_SameAcc = null;
                            BankAccount toAcc_SameAcc = null;
                            System.out.println("Enter the account number you want to deposit or withdraw from:");
                            //read the accNum
                            depOrWithAccountNum = sc.nextInt();
                            System.out.println("Enter the amount (To withdraw enter a negative value)");
                            //read the amount
                            depOrWithAmount = sc.nextDouble();
                            //checking the matching account number in arrayList
                            for (BankAccount listItemsThird : bankAccounts2) {
                                if (listItemsThird.getAccNum() == depOrWithAccountNum) {
                                    fromAcc_SameAcc = listItemsThird;
                                    break;
                                }
                            }

                            if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount()) {
                                System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
                                break;
                            }

                            if (depOrWithAmount < 0) {//the amount is negative
                                fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
                            } else {
                                fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
                            }

                            break;
                    }

                    //inner switch-case ends
                    System.out.println("\n\n");
                    break;

                case 3:
                    //View One account
                    bankAccounts2=(List<BankAccount>)rw.readFromFile();
                    BankAccount viewOneAccountNum = null;

                    System.out.println("Enter the account number you want to see:");
                    viewOneAcc = sc.nextInt();
                    System.out.println("Name\tAccount No\tInitial Amount");
                    for (BankAccount viewOneAccountProperty : bankAccounts2) {

                        if (viewOneAccountProperty.getAccNum() == viewOneAcc) {
                            //viewOneAccountNum=viewOneAccountProperty;
                            viewOneAccountNum = viewOneAccountProperty;

                            System.out.println(viewOneAccountNum);
                        }
                        System.out.println("");

                    }
                    break;
                case 4:
                     bankAccounts2=(List<BankAccount>)rw.readFromFile();
                    //BankAccount AccToDel = null;
                    //Deleting an account
                    Iterator<BankAccount> it = bankAccounts2.iterator();

                    System.out.println("Enter the account you want to delete:");
                    deleteAcc = sc.nextInt();

                    while (it.hasNext()) {
                        BankAccount next = it.next();
                        if (next.getAccNum() == deleteAcc) {
                            it.remove();
                        }
                    }

                    rw.writeToFile(bankAccounts2);


                    break;

                case 5:
                    //View all the accounts/printing them out

                    bankAccounts2=(List<BankAccount>)rw.readFromFile();
                    System.out.println("Name\tAccount No\tInitial Amount");
                    for (BankAccount bankAccount : bankAccounts2) {

                        System.out.println(bankAccount);

                    }

                    System.out.println("\n\n");
                    break;

                case 6:
                    //Quit
                    return;
            }

            //switch-case ends
        }

    }

}

读写器:

public class ReaderWriter{
 public void writeToFile(List<BankAccount> accounts){
   try {
            FileOutputStream fos=new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile_assignment.txt");
            ObjectOutputStream oos=new ObjectOutputStream(fos);
            oos.writeObject(accounts);//take the arrayList 
            oos.flush();
            oos.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public  List<BankAccount> readFromFile(){
        List<BankAccount>readData=null;
        try {



            FileInputStream fis=new FileInputStream("C:\\Users\Documents\\NetBeansProjects\\BankFile_assignment.txt");
            ObjectInputStream ois=new ObjectInputStream(fis);
            //make an arrayList to get those object back
            //arrayList

            readData=(List<BankAccount>)ois.readObject();

         ois.close();
         fis.close();
        } catch (Exception e) {
        e.printStackTrace();
        }
        //return readData;
        return readData;


    }
}

银行账户:

    package bankapp_assignment;

import java.io.Serializable;

public class BankAccount implements Serializable{

    private String name;
    private int accNum;
    private double initiateAmount;

    //constructor
    public BankAccount() {

        this.name = null;
        this.accNum = 0;
        this.initiateAmount = 0;

    }

    public void setName(String name) {
        this.name = name;

    }

    public void setAccNum(int accNum) {

        this.accNum = accNum;
    }

    public String getName(String name){
        return name;

    }


    public int getAccNum() {
        return accNum;
    }


    public void setInitiateAmount(double initiateAmount) {
        this.initiateAmount = initiateAmount;
    }

    public double getInitialAmount(){
        return initiateAmount;
    }

    @Override
    public String toString() {
        return name + "\t\t" + accNum + "\t\t" + initiateAmount;
    }

}

【问题讨论】:

  • 这取决于文件中文本的格式,您能否发布一个示例 tof 文件内容?
  • m.cekiera,是的,请,我已经更新了我的帖子。如果我能得到一些帮助,我将不胜感激。
  • 输入 .txt 文件内容,以显示您如何存储数据,了解如何检索它;)
  • m.cekiera,我已经发布了我的整个主要课程。这描述了文件的内容。我还没有发布 getter 和 setter 的课程,但如果你愿意,我可以做到。请。
  • 什么是银行账户?它是如何存储数据的?

标签: java file-io arraylist fileinputstream fileoutputstream


【解决方案1】:
  1. 你应该重构整个 main 方法。如果我是你,我会用 主要只到午餐程序,其他方法休息。这样您就可以在整个程序中使用类字段,并将代码分成许多方法。
  2. 您应该将主要方法与其他方法分开,至少要方法 每个动作,例如:

    case 1:
        createAccount();
        break;
    (...) 
    public void createAccount(){
    code from your swich case 1
    }
    

    等等。您仍然可以使用开关控制,但应将逻辑代码替换为另一种方法。

  3. 当我运行您的代码时,输​​入/输出不起作用。你能做到吗 保存/加载文件?我不得不改变:

    File file = new File("//file path");
    FileOutputStream fos = new FileOutputStream(file);
    ObjectOutput oos = new ObjectOutputStream(fos);
    

    与输入相同。然后就成功了。

  4. 现在,我们将尝试从文件中处理对 BankAccounts 的操作。我把你的代码从case2/case2改了一点:存款/取款,让我们看看:

    bankAccounts2 = rw.readFromFile();               // loading list from file
    BankAccount edited = new BankAccount();          // creating new object
    System.out.println("Enter the account number you want to deposit or withdraw from:");
    double input = sc.nextInt();                     // you don't need to create new variable every time you take input form user
    for(BankAccount account : bankAccounts2){        // every account in list
           if(account.getAccNum() == input) edited = account;  // if acccNum match, give edited reference to chosen account
    }
    System.out.println("Enter the amount (To withdraw enter a negative value)");
    input = sc.nextDouble();
    
    double result = edited.getInitialAmount() + input;  // result of operation
    if(result < 0){   // check if there is enough money on account
        System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
        break;
    }else{
        edited.setInitiateAmount(result);               // if there is, set new value
    }
    rw.writeToFile(bankAccounts2);                      // save file
    

您可以以类似的方式实现另一个操作。不过还是要考虑将 main 拆分成其他方法,添加类字段等。

编辑:

cmets 中的问题。

因为你用正数充值,负数提现,所以对initialAmount的操作总是一样的:initialAmount + input(如果是负数,就是从amount中减去),所以你可以把它当作一个案例来处理在你的代码中。在您的代码中,您使用此行两次:

fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount); 

所以您已经可以将两种情况合并为一个,以避免不必要的重复。因此,只有在操作有所不同的情况下,当账户上没有足够的钱时,您可以通过以下方式进行检查:

if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount())

但我认为我不会工作,因为在撤回操作中depOrWithAmount 是负数,所以它总是小于fromAcc_SameAcc.getInitialAmount()。你可以使用:

if (depOrWithAmount < 1 - fromAcc_SameAcc.getInitialAmount())

(但我认为它不太可读)或:

if (Math.abs(depOrWithAmount) > fromAcc_SameAcc.getInitialAmount()){}

比较输入的绝对值和initialAmout。但是我用过:

double result = edited.getInitialAmount() + input;
if(result < 0){...}

因为它给了我result 变量,如果有足够的钱我可以重复使用它,为initialAmount 赋予新的价值。如果结果为负数,则表示提现金额大于初始金额,因此没有足够的monay可以提现。

我希望你在我的帖子中找到了一些有用的东西。

【讨论】:

  • m.cekiera,谢谢,真是个好建议!我会按照你的笔记。然而,一个问题:为什么是“if(result
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 2018-01-17
  • 2022-07-07
  • 1970-01-01
  • 2013-05-16
  • 2013-04-16
  • 2011-10-22
相关资源
最近更新 更多