Java 中的数组和银行账户
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25336914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Arrays and bank accounts in Java
提问by Azdamus
I am trying to write a simple Bank Account Management program that does the following:
我正在尝试编写一个简单的银行账户管理程序,它执行以下操作:
Creates a new account with Account number and Balance taken from user and stored in an array Selects an account (from the array) Deletes the account selected Withdraw and Deposit into account selected.
创建一个新帐户,其帐号和余额来自用户并存储在数组中 选择一个帐户(从数组中) 删除选定的帐户 取款和存款到选定的帐户中。
Problem: I don't understand what the my mistakes are.
问题:我不明白我的错误是什么。
I tried using different types of arrays for account number and balance storing, but I didn't not find the answer yet. I search the web and Stackoverflow for references, documentations, simple examples, but could not find any (the ones that I found, use some commands and things that I haven't learned yet so I can understand how they work). I am a beginner, I am still learning and would appreciate some advice. Thanks!
我尝试使用不同类型的数组来存储帐号和余额,但我还没有找到答案。我在网络和 Stackoverflow 上搜索参考资料、文档、简单示例,但找不到任何(我找到的那些,使用了一些我还没有学到的命令和东西,所以我可以理解它们是如何工作的)。我是初学者,我仍在学习,希望得到一些建议。谢谢!
//Bank account class
public class account {
private int ANumber;
private double balance;
public account(double initialBalance, int accno) {
balance = initialBalance;
ANumber = accno;
}
public void deposit (double u_amm){
balance += u_amm;
}
public double withdraw(double amount) {
balance -= amount;
return amount;
}
public double getBalance() {
return balance;
}
public int getAccount(){
return ANumber;
}
}
And this is the Main class
这是主类
import java.util.Scanner;
// main class
public class bankmain {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Menu starts from here
Scanner input = new Scanner(System.in);
System.out.println("Enter the option for the operation you need:");
System.out.println("****************************************************");
System.out.println("[ Options: ne - New Account de - Delete Account ]");
System.out.println("[ dp - Deposit wi - Withdraw ]");
System.out.println("[ se - Select Account ex - Quit ]");
System.out.println("****************************************************");
System.out.print("> "); //indicator for user input
String choice = input.next();
//Options
while(true){
if(choice == "ne"){
int nacc;
int bal;
int [][]array = new int[nacc][bal]; // Array for account and balance
System.out.print("Insert account number: ");
nacc =input.nextInt(); //-- Input nr for array insertion
System.out.print("Enter initial balance: ");
bal=input.nextInt(); //-- Input nr for array insertion
System.out.println("Current account: " + nacc + " " + "Balance " + bal);
break;
}
// account selection
if(choice.equals("se")){
System.out.println("Enter number of account to be selected: ");
//user input for account nr from array
System.out.println("Account closed.");
}
//close account
if(choice.equals("de")){
//array selected for closing
System.out.println("Account closed.");
}
// deposit
if(choice.equals("dp")){
System.out.print("Enter amount to deposit: ");
double amount = scan.nextDouble();
if(amount <= 0){
System.out.println("You must deposit an amount greater than 0.");
} else {
System.out.println("You have deposited " + (amount + account.getBalance()));
}
}
// withdrawal
if(choice.equals("wi")){
System.out.print("Enter amount to be withdrawn: ");
double amount = scan.nextDouble();
if (amount > account.balance()){
System.out.println("You can't withdraw that amount!");
} else if (amount <= account.balance()) {
account.withdraw(amount);
System.out.println("NewBalance = " + account.getBalance());
}
}
//quit
if(choice == "ex"){
System.exit(0);
}
} // end of menu loop
}// end of main
} // end of class
采纳答案by Micha? Schielmann
Your code was wrong on many levels - first try to work on your formatting and naming conventions so you don't learn bad habbits. Dont use small leters for naming classes, try to use full words to describe variables and fields, like in that Account.class example:
你的代码在很多层面上都是错误的——首先尝试处理你的格式和命名约定,这样你就不会学习坏习惯。不要使用小写字母来命名类,尝试使用完整的单词来描述变量和字段,例如 Account.class 示例:
public class Account {
private Integer accountNumber;
private Double balance;
public Account(final Integer accountNumber, final Double initialBalance) {
this.accountNumber = accountNumber;
balance = initialBalance;
}
public Double deposit (double depositAmmount) {
balance += depositAmmount;
return balance;
}
public Double withdraw(double withdrawAmmount) {
balance -= withdrawAmmount;
return balance;
}
public Double getBalance() {
return balance;
}
public Integer getAccountNumber() {
return accountNumber;
}
}
Also try to use the same formatting(ie. spaces after brackets) in all code, so that it's simpler for you to read.
还尝试在所有代码中使用相同的格式(即括号后的空格),以便您更轻松地阅读。
Now - what was wrong in your app:
现在 - 您的应用程序出了什么问题:
Define the proper holder for your accounts i.e. HashMap that will hold the information about all accounts and will be able to find them by accountNumber.
HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>()
;This one should be inside your while loop, as you want your user to do multiple tasks. You could ommit the println's but then the user would have to go back to the top of the screen to see the options.
System.out.println("Enter the option for the operation you need:"); System.out.println("****************************************************"); System.out.println("[ Options: ne - New Account de - Delete Account ]"); System.out.println("[ dp - Deposit wi - Withdraw ]"); System.out.println("[ se - Select Account ex - Quit ]"); System.out.println("****************************************************"); System.out.print("> "); //indicator for user input String choice = input.nextLine(); System.out.println("Your choice: " + choice);
You shouldn't compare Strings using '==' operator as it may not return expected value. Take a look at: How do I compare strings in Java?or What is the difference between == vs equals() in Java?. For safty use Objects equals instead, ie:
choice.equals("ne")
There was no place where you created the account:
Account newAccount = new Account(newAccountNumber, initialBalance);
You didn't use if-else, just if's. It should look more like that (why to check if the choice is 'wi' if it was already found to be 'ne'):
if(choice.equals("ne")) { //doStuff } else if choice.equals("se") { //doStuff } //and so on.
If your using Java version >= 7 then instead of if-else you can use switch to compare Strings.
There was no notification of the wrong option:
} else { System.out.println("Wrong option chosen."); }
You didn't close your Scanner object. This really doesn't matter here, as it's in main method and will close with it, but it's a matter of good habbits to always close your streams, data sources etc when done using it:
input.close();
为您的帐户定义适当的持有者,即 HashMap,它将保存有关所有帐户的信息,并能够通过 accountNumber 找到它们。
HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>()
;这个应该在你的 while 循环中,因为你希望你的用户执行多项任务。您可以省略 println ,但用户必须返回屏幕顶部才能看到选项。
System.out.println("Enter the option for the operation you need:"); System.out.println("****************************************************"); System.out.println("[ Options: ne - New Account de - Delete Account ]"); System.out.println("[ dp - Deposit wi - Withdraw ]"); System.out.println("[ se - Select Account ex - Quit ]"); System.out.println("****************************************************"); System.out.print("> "); //indicator for user input String choice = input.nextLine(); System.out.println("Your choice: " + choice);
您不应该使用 '==' 运算符比较字符串,因为它可能不会返回预期值。看一看:我如何比较Java中的字符串?或者Java 中 == 和 equals() 有什么区别?. 为了安全使用 Objects equals 代替,即:
choice.equals("ne")
没有您创建帐户的地方:
Account newAccount = new Account(newAccountNumber, initialBalance);
你没有使用 if-else,只是 if's。它应该看起来更像(如果已经发现它是 'ne',为什么要检查它是否是 'wi'):
if(choice.equals("ne")) { //doStuff } else if choice.equals("se") { //doStuff } //and so on.
如果您使用的 Java 版本 >= 7,那么您可以使用 switch 来比较字符串而不是 if-else。
没有错误选项的通知:
} else { System.out.println("Wrong option chosen."); }
您没有关闭 Scanner 对象。这在这里真的无关紧要,因为它在 main 方法中并会随之关闭,但是在使用完后始终关闭流、数据源等是一个好习惯:
input.close();
So the whole code can look like this:
所以整个代码可以是这样的:
import java.util.HashMap;
import java.util.Scanner;
// main class
public class BankAccount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>();
//Options
while(true) {
System.out.println("Enter the option for the operation you need:");
System.out.println("****************************************************");
System.out.println("[ Options: ne - New Account de - Delete Account ]");
System.out.println("[ dp - Deposit wi - Withdraw ]");
System.out.println("[ se - Select Account ex - Quit ]");
System.out.println("****************************************************");
System.out.print("> "); //indicator for user input
String choice = input.next();
System.out.println("Your choice: " + choice);
if(choice.equals("ne")) {
Integer newAccountNumber;
Double initialBalance;
Account newAccount;
// Array for account and balance
System.out.print("Insert account number: ");
newAccountNumber = input.nextInt(); //-- Input nr for array insertion
System.out.print("Enter initial balance: ");
initialBalance=input.nextDouble(); //-- Input nr for array insertion
newAccount = new Account(newAccountNumber, initialBalance);
accountMap.put(newAccountNumber, newAccount);
System.out.println("New Account " + newAccountNumber + " created with balance: " + initialBalance);
}
//select account
else if(choice.equals("se")) {
System.out.println("Enter number of account to be selected: ");
Integer accountToGetNumber = input.nextInt();
Account returnedAccount = accountMap.get(accountToGetNumber);
if (returnedAccount != null)
{
System.out.println("Account open. Current balance: " + returnedAccount.getBalance());
}
else
{
//user input for account nr from array
System.out.println("Account does not exist.");
}
}
//close account
else if(choice.equals("de"))
{
System.out.println("Enter number of account to be selected: ");
Integer accountToDeleteNumber = input.nextInt();
Account removedAccount = accountMap.remove(accountToDeleteNumber);
if (removedAccount != null)
{
System.out.println("Account " + removedAccount.getAccountNumber() + " has been closed with balance: " + removedAccount.getBalance());
}
else
{
//user input for account nr from array
System.out.println("Account does not exist.");
}
}
// deposit
else if(choice.equals("dp")) {
System.out.println("Enter number of account to deposit: ");
Integer accountToDeposit = input.nextInt();
System.out.print("Enter amount to deposit: ");
double amount = input.nextDouble();
if(amount <= 0){
System.out.println("You must deposit an amount greater than 0.");
} else {
accountMap.get(accountToDeposit).deposit(amount);
System.out.println("You have deposited " + (amount));
System.out.println("Current balance " + accountMap.get(accountToDeposit).getBalance());
}
}
// withdrawal
else if(choice.equals("wi")) {
System.out.println("Enter number of account to withdraw: ");
Integer accountToWithdraw = input.nextInt();
System.out.print("Enter amount to withdraw: ");
double amount = input.nextDouble();
if(amount <= 0) {
System.out.println("You must deposit an amount greater than 0.");
} else {
accountMap.get(accountToWithdraw).withdraw(amount);
System.out.println("You have deposited " + (amount));
System.out.println("Current balance " + accountMap.get(accountToWithdraw).getBalance());
}
}
//quit
else if(choice.equals("ex")) {
break;
} else {
System.out.println("Wrong option.");
} //end of if
} //end of loop
input.close();
} //end of main
} //end of class
There still is much to improve, i.e. input validation - but this should work for the begining.
还有很多需要改进,即输入验证 - 但这应该适用于开始。
回答by OO7
You have written the above code, but it has many mistakes. You need to learn the The basics of Java programming.
你已经写了上面的代码,但是它有很多错误。您需要学习Java 编程的基础知识。
I have modified your programto perform below operations :-
我已修改您的程序以执行以下操作:-
- Create new account.
- Select existing account.
- Deposit amount.
- Withdraw amount.
- View balance.
- Delete account.
- Exit.
- 建立新帐户。
- 选择现有帐户。
- 存款金额。
- 取款数量。
- 查看余额。
- 删除帐户。
- 出口。
Account.java :
帐户.java :
/**
* This class performs bank operations
*/
public class Account {
private int accNumber;
private double balance;
public Account(double initialBalance, int accNo) {
balance = initialBalance;
accNumber = accNo;
}
public void deposit(double amount) {
balance += amount;
}
public double withdraw(double amount) {
balance -= amount;
return amount;
}
public double getBalance() {
return balance;
}
public int getAccNumber() {
return accNumber;
}
}
BankMain.java :
银行主.java :
public class BankMain {
private static double amount;
private static ArrayList<Account> accountList = new ArrayList<>();
private static Account selectedAccount;
private static boolean flag = false;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Menu starts from here
Scanner input = new Scanner(System.in);
System.out.println("Enter the option for the operation you need:");
System.out
.println("****************************************************");
System.out
.println("[ Options: new - New Account del - Delete Account ]");
System.out
.println("[ dp - Deposit wi - Withdraw bal - Check balance ]");
System.out
.println("[ se - Select Account exit - Quit ]");
System.out
.println("****************************************************");
Account account = null;
while (true) {
System.out.println("> "); // indicator for user input
String choice = input.next();
// Options
switch (choice) {
case "new":
// Create new account
int accNo = 0;
int bal = 0;
System.out.println("Enter account number : ");
accNo = input.nextInt();
System.out.println("Enter initial balance: ");
bal = input.nextInt();
System.out.println("Current account: " + accNo + " "
+ "Balance " + bal);
account = new Account(bal, accNo);
accountList.add(account);
break;
case "se":
// select account
System.out
.println("Enter account number for further operations : ");
int selectedAcc = scan.nextInt();
System.out.println("Selected account : " + selectedAcc);
for (Object object : accountList) {
selectedAccount = (Account) object;
if (selectedAccount.getAccNumber() == selectedAcc) {
flag = true;
break;
} else {
flag = false;
}
}
if (!flag) {
System.out.println("Account doesn't exists.");
}
if (accountList.size() == 0) {
System.out.println("Zero account exists.");
}
break;
case "del":
// close account
System.out
.println("Enter account number for further operations : ");
int selectedAcc1 = scan.nextInt();
System.out.println("Selected account : " + selectedAcc1);
Iterator<Account> iterator = accountList.iterator();
while (iterator.hasNext()) {
selectedAccount = (Account) iterator.next();
if (selectedAccount.getAccNumber() == selectedAcc1) {
iterator.remove();
flag = true;
break;
}
}
if (!flag) {
System.out.println("Account doesn't exists.");
}
System.out.println("Account " + selectedAcc1 + " closed.");
break;
case "dp":
// Deposit amount
System.out.println("Enter amount to deposit : ");
amount = scan.nextDouble();
if (amount <= 0) {
System.out
.println("You must deposit an amount greater than 0.");
} else {
if (flag) {
selectedAccount.deposit(amount);
System.out.println("You have deposited " + amount
+ ". Total balance : "
+ (selectedAccount.getBalance()));
} else {
System.out.println("Please select account number.");
}
}
break;
case "wi":
// Withdraw amount
System.out.println("Enter amount to be withdrawn: ");
amount = scan.nextDouble();
if (amount > account.getBalance() && amount <= 0) {
System.out.println("You can't withdraw that amount!");
} else if (amount <= selectedAccount.getBalance()) {
if (flag) {
selectedAccount.withdraw(amount);
System.out.println("You have withdraw : " + amount
+ " NewBalance : "
+ selectedAccount.getBalance());
} else {
System.out.println("Please select account number.");
}
}
break;
case "bal":
// check balance in selected account
if (flag) {
System.out.println("Your current account balance : "
+ selectedAccount.getBalance());
} else {
System.out.println("Please select account number.");
}
break;
case "exit":
default:
// quit
System.out.println("Thank You. Visit Again!");
flag = false;
input.close();
scan.close();
System.exit(0);
break;
}
} // end of menu loop
}// end of main
} // end of class
I have tested this code & it is working fine.
我已经测试了这段代码,它工作正常。
Output :
输出 :
Enter the option for the operation you need:
****************************************************
[ Options: new - New Account del - Delete Account ]
[ dp - Deposit wi - Withdraw bal - Check balance ]
[ se - Select Account exit - Quit ]
****************************************************
> new
Enter account number : 101
Enter initial balance: 10000
Current account: 101 Balance 10000
> new
Enter account number : 102
Enter initial balance: 25000
Current account: 102 Balance 25000
> se
Enter account number for further operations : 103
Selected account : 103
Account doesn't exists.
> se
Enter account number for further operations : 101
Selected account : 101
> bal
Your current account balance : 10000.0
> dp
Enter amount to deposit : 2500
You have deposited 2500.0. Total balance : 12500.0
> wi
Enter amount to be withdrawn: 500
You have withdraw : 500.0 NewBalance : 12000.0
> se
Enter account number for further operations : 102
Selected account : 102
> bal
Your current account balance : 25000.0
> del
Enter account number for further operations : 101
Selected account : 101
Account 101 closed.
> se
Enter account number for further operations : 101
Selected account : 101
Account doesn't exists.
> exit
Thank You. Visit Again!