gpt4 book ai didi

java - 如何在文件中写入的对象之间进行算术运算?

转载 作者:太空宇宙 更新时间:2023-11-04 13:54:26 24 4
gpt4 key购买 nike

在我的程序中,用户输入值并将这些值存储在 arrayList 中。 ArrayList 对象被写入文件中。我已经使用 file-i/o、object-i/o 流在文件中进行写入和读取。现在我想在对象之间执行加法和减法(int 或 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;
}

}

最佳答案

  1. 你应该重构整个 main 方法。如果我是你,我会使用主要仅以午餐程序为主,休息过程以其他方式进行。这样您就可以在整个程序中使用类字段,并将代码划分为许多方法。
  2. 您应该将 main 方法划分为其他方法,至少划分为方法每个操作,例如:

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

    等等。您仍然可以使用 swich 控件,但应将逻辑代码替换为其他方法。

  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 划分为其他方法,添加类字段等。

编辑:

对于评论中的问题。

因为您使用正数进行存款,使用负数进行提款,所以对初始金额的操作将始终相同:初始金额+输入(如果为负数,则将从金额中减去),因此您可以将其视为代码中的一种情况。在您的代码中,您使用此行两次:

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 提供新值。如果结果为负数,则表示提现金额大于初始金额,因此提现金额不足。

我希望您在我的帖子中找到有用的内容。

关于java - 如何在文件中写入的对象之间进行算术运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29986531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com