gpt4 book ai didi

java - 如何追踪银行账户余额?

转载 作者:行者123 更新时间:2023-12-02 05:08:22 24 4
gpt4 key购买 nike

我将创建一个程序来跟踪银行帐户的余额。程序应使用一个循环,该循环将持续到用户通过对问题您想继续吗?回答来选择退出。

在循环中,应要求用户输入金额(正数表示存款,负数表示提款)。该金额应从帐户余额变量中添加/减去。所有存款/取款都应保存为历史记录,以便我们稍后打印。当用户选择退出循环时,将打印当前帐户余额以及帐户历史记录(来自数组/ArrayList)。

现在,我想使用具有十个槽的数组来实现历史功能。

我的问题是如何跟踪所有存款、取款和经常账户余额(使用具有十个插槽的历史记录功能的数组),以便在用户退出时将其打印出来程序?

我的代码:

银行应用程序类:

package bankapp;

import java.util.Scanner;

public class BankApp {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
askingUser au = new askingUser();

System.out.println("WELCOME TO OUR BANK!\nYou have 100 SEK by default in your account.");

while (true) {

au.userInput();

System.out.println("Do you want to continue? Answer by Yes or No.");
String yesOrNo = input.next();

if (yesOrNo.equalsIgnoreCase("yes")) {

au.userInput();

} else if (yesOrNo.equalsIgnoreCase("no")) {
System.out.println("History: ");

//print out the transaction history
System.exit(0);

} else {

System.out.println("Invalid character input.");

}

}

}
}

询问用户类:

package bankapp;

import java.util.Scanner;

public class askingUser {

Scanner input = new Scanner(System.in);
double initialBal = 100;

public void userInput() {
System.out.println("Enter your amount: (+ve for deposit & -ve for withdraw)");
double inputAmount = input.nextDouble();

if (inputAmount >= 0) {

double newPosAm = initialBal + inputAmount;
System.out.println("Your current balance is: " + newPosAm + " SEK");

} else {

double newNegAm = initialBal + inputAmount;
System.out.println("Your current balace is: " + newNegAm + " SEK");
}

}

}

最佳答案

如果您使用数组,则必须跟踪存储在其中的元素数量,并在必要时调整数组的大小。最简单的方法是将历史记录作为字符串保存在 ArrayList 中。 。您可以在每笔交易中向该列表添加一条消息:

ArrayList<String> history = new ArrayList<String>();

void addToHistory(String transaction) {
history.add(transaction);
}

void printHistory() {
for(String s : history) {
System.out.println(s);
}
}

addToHistory("Withdrawal: 100 SEK" );
addToHistory("Deposit: 200 SEK" );
printHistory();

关于java - 如何追踪银行账户余额?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27564670/

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