I am working on a school project. I have all the functionality working, I made it on Eclipse and it runs very well but when I submit the project through Mimir which is an online tool to grade your project, during deposits and withdraws it gives the following error:
Enter the amount you want to Deposit :$Exception in thread "main" java.util.NoSuchElementException
13 at java.util.Scanner.throwFor(Scanner.java:862)
14 at java.util.Scanner.next(Scanner.java:1485)
15 at java.util.Scanner.nextDouble(Scanner.java:2345)
16 at BankAccount.deposit(BankAccount.java:24)
17 at SavingsAccountDemo.main(SavingsAccountDemo.java:30)
The project does says the following: Please make sure that your classes throw appropriate exceptions when an attempt is made to insert invalid data.
I tried to add the try and catch with java.util.InputMismatchException e and java.util.NoSuchElementException but it doesn't seem to be fixing it. I think it's because the userInput is a double and they are entering something different. Any ideas how can I fix that? I am going crazy, been trying to fix it for hours. Here is the code:
///SavingsAccountDemo class
import java.util.*;
public class SavingsAccountDemo {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double startingBalance;
double interestRate;
String userInput;
System.out.print("Enter beginning balance :$");
startingBalance = keyboard.nextDouble();
System.out.print("Enter interest rate(whole number) :%");
interestRate = keyboard.nextDouble();
double bal = startingBalance;
double rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
BankDemo sv = new BankDemo(bal, rate);
while(startingBalance > -1) {
try {
System.out.println("Enter D for deposit" + "\nEnter W to Withdraw" + "\nEnter B for Balance" +
"\nEnter M for Monthly Process" + "\nEnter E to Exit");
userInput = keyboard.next().toLowerCase();
if("d".equals(userInput)) {
ba.deposit();
} else if("w".equals(userInput)) {
ba.withdraw();
} else if("b".equals(userInput)) {
ba.totalBalance();
} else if("m".equals(userInput)) {
ba.monthlyProcess();
} else if("e".equals(userInput)) {
ba.exit();
break;
}
else {
System.out.print("Error, option not valid\n");
}
}
catch (java.util.InputMismatchException e) {
System.out.print("Error");
}
}
}
}
///BankAccount class
import java.util.*;
public class BankAccount {
protected double balance;
protected double numDeposits;
protected double numWithdrawals;
protected double annualRate;
protected double monthlyServCharg;
protected boolean active;
Scanner keyboard = new Scanner(System.in);
public BankAccount(double startingBalance, double interestRate) {
balance = startingBalance;
annualRate = interestRate /= 100.0;
if(balance < 25) {
active = false;
} else
active = true;
}
public void deposit() {
try {
double valueD;
System.out.print("Enter the amount you want to Deposit :$");
valueD = keyboard.nextDouble();
if(valueD < 0) {
System.out.println("Error: Must enter positive value\n");
}
if( balance + valueD >= 25 && !active) {
System.out.print("Your account is now ACTIVE\n");
active = true;
}
balance += valueD;
numDeposits++;
}
catch (java.util.InputMismatchException e){
keyboard.nextLine();
}
}
public void withdraw() {
try {
double valueW;
System.out.print("Enter the amount you want to withdraw :$");
valueW = keyboard.nextDouble();
if(valueW < 0) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numWithdrawals++;
if(balance < 0) {
System.out.print("ERROR: Transaction declined!! This transaction will cause overdraft or zero balance\n");
balance += valueW;
} else if(balance <= 25 && active) {
System.out.print("Your balance is less than minimum balance. Your account is now INACTIVE\n");
active = false;
}
if(numWithdrawals > 4) {
balance --;
System.out.print("You have exceeded monthly limit of withdrawals. Fee of $1 charged\n");
}
}
catch (java.util.InputMismatchException e) {
keyboard.nextLine();
}
}
public void totalBalance() {
System.out.printf("Your Balance is: %.2f\n", balance);
}
public void calcInterest() {
double monRate = annualRate / 12;
double monInt = balance * monRate;
balance += monInt;
}
public void monthlyProcess() {
calcInterest();
balance -= monthlyServCharg;
numWithdrawals = 0;
numDeposits = 0;
monthlyServCharg = 0;
System.out.printf("Your Balance after Monthly process is: %.2f\n", balance);
}
public void exit() {
totalBalance();
System.out.print("Thank you. Bye");
}
}
When scanning an input with Scanner, the expected result is always a String.
Therefore, you have to check if the field is a double before assuming it is. You can use a cast and check with a try catch if casting raises an NumberFormatException error. If it is the case, the input is not valid. Otherwise, you can use that newly casted double in your program.
I am working on a school project. I have all the functionality working but when I submit the project through Mimir, during deposits and withdraws it gives the following error:
Enter the amount you want to Deposit :$Exception in thread "main" java.util.NoSuchElementException
13 at java.util.Scanner.throwFor(Scanner.java:862)
14 at java.util.Scanner.next(Scanner.java:1485)
15 at java.util.Scanner.nextDouble(Scanner.java:2345)
16 at BankAccount.deposit(BankAccount.java:24)
17 at SavingsAccountDemo.main(SavingsAccountDemo.java:30)
The project does says the following: Please make sure that your classes throw appropriate exceptions when an attempt is made to insert invalid data.
I tried to add the try and catch with java.util.InputMismatchException e but it doesn't seem to be fixing it. I think it's because the userInput is a double and they are entering something different. Any ideas how can I fix that? Here is the code:
///SavingsAccountDemo class
import java.util.*;
public class SavingsAccountDemo {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double startingBalance;
double interestRate;
String userInput;
System.out.print("Enter beginning balance :$");
startingBalance = keyboard.nextDouble();
System.out.print("Enter interest rate(whole number) :%");
interestRate = keyboard.nextDouble();
double bal = startingBalance;
double rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
BankDemo sv = new BankDemo(bal, rate);
while(startingBalance > -1) {
try {
System.out.println("Enter D for deposit" + "\nEnter W to Withdraw" + "\nEnter B for Balance" +
"\nEnter M for Monthly Process" + "\nEnter E to Exit");
userInput = keyboard.next().toLowerCase();
if("d".equals(userInput)) {
ba.deposit();
} else if("w".equals(userInput)) {
ba.withdraw();
} else if("b".equals(userInput)) {
ba.totalBalance();
} else if("m".equals(userInput)) {
ba.monthlyProcess();
} else if("e".equals(userInput)) {
ba.exit();
break;
}
else {
System.out.print("Error, option not valid\n");
}
}
catch (java.util.InputMismatchException e) {
System.out.print("Error");
}
}
}
}
///BankAccount class
import java.util.*;
public class BankAccount {
protected double balance;
protected double numDeposits;
protected double numWithdrawals;
protected double annualRate;
protected double monthlyServCharg;
protected boolean active;
Scanner keyboard = new Scanner(System.in);
public BankAccount(double startingBalance, double interestRate) {
balance = startingBalance;
annualRate = interestRate /= 100.0;
if(balance < 25) {
active = false;
} else
active = true;
}
public void deposit() {
try {
double valueD;
System.out.print("Enter the amount you want to Deposit :$");
valueD = keyboard.nextDouble();
if(valueD < 0) {
System.out.println("Error: Must enter positive value\n");
}
if( balance + valueD >= 25 && !active) {
System.out.print("Your account is now ACTIVE\n");
active = true;
}
balance += valueD;
numDeposits++;
}
catch (java.util.InputMismatchException e){
keyboard.nextLine();
}
}
public void withdraw() {
try {
double valueW;
System.out.print("Enter the amount you want to withdraw :$");
valueW = keyboard.nextDouble();
if(valueW < 0) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numWithdrawals++;
if(balance < 0) {
System.out.print("ERROR: Transaction declined!! This transaction will cause overdraft or zero balance\n");
balance += valueW;
} else if(balance <= 25 && active) {
System.out.print("Your balance is less than minimum balance. Your account is now INACTIVE\n");
active = false;
}
if(numWithdrawals > 4) {
balance --;
System.out.print("You have exceeded monthly limit of withdrawals. Fee of $1 charged\n");
}
}
catch (java.util.InputMismatchException e) {
keyboard.nextLine();
}
}
public void totalBalance() {
System.out.printf("Your Balance is: %.2f\n", balance);
}
public void calcInterest() {
double monRate = annualRate / 12;
double monInt = balance * monRate;
balance += monInt;
}
public void monthlyProcess() {
calcInterest();
balance -= monthlyServCharg;
numWithdrawals = 0;
numDeposits = 0;
monthlyServCharg = 0;
System.out.printf("Your Balance after Monthly process is: %.2f\n", balance);
}
public void exit() {
totalBalance();
System.out.print("Thank you. Bye");
}
}
In my code, I was able to use the scanner feature to prompt the user to type a piece of text, however, I was only able to make it so the user can type once. To type again I would have to close the terminal, and open it again, how can I make it so that I can just type infinitely so that I wouldn't have to close it and reopen it every time in order to type again?
For context, this is my code, it is about a ticket machine which displays certain data, like the name of the person, the price, the total balance, etc. Currently I am doing the places. This means that I want the user to type any city in England, and a price would appear. But as I said, the user can only jarringly type one thing at a time, when they should be able to type without any limit.
import java.util.Scanner;
import java.lang.String;
public class TicketMachine
{
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost)
{
price = cost;
balance = 0;
total = 0;
}
/**
* #Return The price of a ticket.
*/
public int getPrice()
{
return price;
}
/**
* Return The amount of money already inserted for the
* next ticket.
*/
public int getBalance()
{
return balance;
}
/**
* Receive an amount of money from a customer.
* Check that the amount is sensible.
*/
public void insertMoney(int amount)
{
if(amount > 0) {
balance = balance + amount;
}
else {
System.out.println("Use a positive amount rather than: " +
amount);
}
}
/**
* Print a ticket if enough money has been inserted, and
* reduce the current balance by the ticket price. Print
* an error message if more money is required.
*/
public void printTicket()
{
if(balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
}
else {
System.out.println("You must insert at least: " +
(price - balance) + " more cents.");
}
}
/**
* Return the money in the balance.
* The balance is cleared.
*/
public int refundBalance()
{
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String [] args)
{
Scanner myScanner = new Scanner(System.in);
String answer = myScanner.nextLine();
if( answer.equals("London") )
{
System.out.println("£15");
}
if( answer.equals("Manchester") )
{
System.out.println("£20");
}
if( answer.equals("Brighton") )
{
System.out.println("£25");
}
if( answer.equals("Cornwall") )
{
System.out.println("£30");
}
if( answer.equals("Crystal Palace") )
{
System.out.println("£35");
}
if( answer.equals("Chealsea") )
{
System.out.println("£40");
}
if( answer.equals("Birmingham") )
{
System.out.println("£45");
}
if( answer.equals("Liverpool") )
{
System.out.println("£50");
}
if( answer.equals("Bristol") )
{
System.out.println("£55");
}
if( answer.equals("Leister") )
{
System.out.println("£60");
}
if( answer.equals("Newcastle") )
{
System.out.println("£65");
}
if( answer.equals("Cambridge") )
{
System.out.println("£70");
}
if( answer.equals("Bradford") )
{
System.out.println("£75");
}
if( answer.equals("Leeds") )
{
System.out.println("£80");
}
if( answer.equals("Oxford") )
{
System.out.println("£85");
}
if( answer.equals("Nottingham") )
{
System.out.println("£90");
}
if( answer.equals("Peterborough") )
{
System.out.println("£95");
}
if( answer.equals("Sheffield") )
{
System.out.println("£100");
}
}
}
Using a while true or a infinite loop isn't a good practice. You can use a do-while and check a flag (e.g. "exit") to close the program e.g.
import java.util.Scanner;
import java.lang.String;
public class TicketMachine {
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost) {
price = cost;
balance = 0;
total = 0;
}
/**
* #Return The price of a ticket.
*/
public int getPrice() {
return price;
}
/**
* Return The amount of money already inserted for the next ticket.
*/
public int getBalance() {
return balance;
}
/**
* Receive an amount of money from a customer. Check that the amount is sensible.
*/
public void insertMoney(int amount) {
if (amount > 0) {
balance = balance + amount;
} else {
System.out.println("Use a positive amount rather than: "
+ amount);
}
}
/**
* Print a ticket if enough money has been inserted, and reduce the current balance by the
* ticket price. Print an error message if more money is required.
*/
public void printTicket() {
if (balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
} else {
System.out.println("You must insert at least: "
+ (price - balance) + " more cents.");
}
}
/**
* Return the money in the balance. The balance is cleared.
*/
public int refundBalance() {
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Enter your city, please:");
answer = myScanner.nextLine();
if (answer.equals("London")) {
System.out.println("£15");
}
else if (answer.equals("Manchester")) {
System.out.println("£20");
}
else if (answer.equals("Brighton")) {
System.out.println("£25");
}
else if (answer.equals("Cornwall")) {
System.out.println("£30");
}
else if (answer.equals("Crystal Palace")) {
System.out.println("£35");
}
else if (answer.equals("Chealsea")) {
System.out.println("£40");
}
else if (answer.equals("Birmingham")) {
System.out.println("£45");
}
else if (answer.equals("Liverpool")) {
System.out.println("£50");
}
else if (answer.equals("Bristol")) {
System.out.println("£55");
}
else if (answer.equals("Leister")) {
System.out.println("£60");
}
else if (answer.equals("Newcastle")) {
System.out.println("£65");
}
else if (answer.equals("Cambridge")) {
System.out.println("£70");
}
else if (answer.equals("Bradford")) {
System.out.println("£75");
}
else if (answer.equals("Leeds")) {
System.out.println("£80");
}
else if (answer.equals("Oxford")) {
System.out.println("£85");
}
else if (answer.equals("Nottingham")) {
System.out.println("£90");
}
else if (answer.equals("Peterborough")) {
System.out.println("£95");
}
else if (answer.equals("Sheffield")) {
System.out.println("£100");
}else {
System.out.println("ERROR: INVALID INPUT");
}
} while (answer != "exit");
}
}
PS use a switch case instead of if(){} e.g
import java.util.Scanner;
import java.lang.String;
public class TicketMachine {
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost) {
price = cost;
balance = 0;
total = 0;
}
/**
* #Return The price of a ticket.
*/
public int getPrice() {
return price;
}
/**
* Return The amount of money already inserted for the next ticket.
*/
public int getBalance() {
return balance;
}
/**
* Receive an amount of money from a customer. Check that the amount is sensible.
*/
public void insertMoney(int amount) {
if (amount > 0) {
balance = balance + amount;
} else {
System.out.println("Use a positive amount rather than: "
+ amount);
}
}
/**
* Print a ticket if enough money has been inserted, and reduce the current balance by the
* ticket price. Print an error message if more money is required.
*/
public void printTicket() {
if (balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
} else {
System.out.println("You must insert at least: "
+ (price - balance) + " more cents.");
}
}
/**
* Return the money in the balance. The balance is cleared.
*/
public int refundBalance() {
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Enter your city, please:");
answer = myScanner.nextLine();
switch (answer) {
case "London":
System.out.println("£15");
break;
case "Manchester":
System.out.println("£20");
break;
case "Brighton":
System.out.println("£25");
break;
case "Cornwall":
System.out.println("£30");
break;
case "Crystal Palace":
System.out.println("£35");
break;
case "Chealsea":
System.out.println("£40");
break;
case "Birmingham":
System.out.println("£45");
break;
case "Liverpool":
System.out.println("£50");
break;
case "Bristol":
System.out.println("£55");
break;
case "Leister":
System.out.println("£20");
break;
case "Newcastle":
System.out.println("£65");
break;
case "Cambridge":
System.out.println("£70");
break;
case "Bradford":
System.out.println("£75");
break;
case "Leeds":
System.out.println("£80");
break;
case "Oxford":
System.out.println("£85");
break;
case "Nottingham":
System.out.println("£90");
break;
case "Peterborough":
System.out.println("£95");
break;
case "Sheffield":
System.out.println("£100");
break;
default:
System.out.println("ERROR: INVALID INPUT");
break;
}
} while (answer != "exit");
}
}
I am creating a bank account program for my java class that is suppose to manage up to 5 different bank accounts. The program has to allow the creation of a new account, which I have done, allow deposit and withdraw, which is also done, the 2 parts I cannot get to work are 1: the bank can only have up to 5 accounts, so if a 6th is trying to be created, a message comes up saying that 5 are already created, and 2: one of the options has to print out all the account balances of current accounts in the bank.
This is my code as of now:
import java.util.Scanner;
public class Bankapp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bank myBank = new Bank();
int user_choice = 2;
do {
//display menu to user
//ask user for his choice and validate it (make sure it is between 1 and 6)
System.out.println();
System.out.println("1) Open a new bank account");
System.out.println("2) Deposit to a bank account");
System.out.println("3) Withdraw to bank account");
System.out.println("4) Print account balance");
System.out.println("5) Quit");
System.out.println();
System.out.print("Enter choice [1-5]: ");
user_choice = s.nextInt();
switch (user_choice) {
case 1:
System.out.println("Enter a customer name");
String cn = s.next();
System.out.println("Enter a opening balance");
double d = s.nextDouble();
System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
break;
case 2: System.out.println("Enter a account number");
int an = s.nextInt();
System.out.println("Enter a deposit amount");
double da = s.nextDouble();
myBank.depositTo(an, da);
break;
case 3: System.out.println("Enter a account number");
int acn = s.nextInt();
System.out.println("Enter a withdraw amount");
double wa = s.nextDouble();
myBank.withdrawFrom(acn, wa);
break;
case 4: System.out.println("Enter a account number");
int anum = s.nextInt();
myBank.printAccountInfo(anum);
break;
case 5:
System.out.println("Here are the balances " + "for each account:");
case 6:
System.exit(0);
}
}
while (user_choice != '6');
}
static class Bank {
private BankAccount[] accounts; // all the bank accounts at this bank
private int numOfAccounts = 5; // the number of bank accounts at this bank
// Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
accounts = new BankAccount[5];
numOfAccounts = 0;
}
// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].withdraw(amount);
System.out.println("Amount withdrawn successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].deposit(amount);
System.out.println("Amount deposited successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
public void printAccountInfo(int accountNum, int n) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int accountNum;
private String customerName;
private double balance;
private static int noOfAccounts=0;
public String getAccountInfo(){
return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
accountNum = noOfAccounts;
}
public int getAccountNum(){
return accountNum;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
}
}
public void withdraw(double amount)
{
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else
{
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
}
}
}
}//end of class
The program runs fine, I just need to add these two options, and cannot get them to work properly, how would I go about doing this? Also, options 3 and 4 should not work if no accounts have been created yet. Thanks in advance.
UPDATE: this is what I tried, I keep getting a this method must return type int error.
public int openNewAccount(String customerName, double openingBalance) {
if(numOfAccounts > 5)
{
System.out.println("5 accounts already exist");
}
else
{
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
}
UPDATE 2: I added a return statement, now when it runs it will open accounts up to number 5, but for every account after number 5 it just says the account number is 5 again instead of not opening an account.
public int openNewAccount(String customerName, double openingBalance) {
if(numOfAccounts > 5)
{
System.out.println("5 accounts already exist");
}
else
{
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
return numOfAccounts;
}
Its pretty simple. Create a list of size 5 and add the account into that list when user is created one. Before adding just make a check whether list size <= 5. If it is true, go ahead and add the account, otherwise throw an error
For option 2, just iterate through the list and display the results
1; in the openNewBank account method; before creating the new Bank account and increasing the count by 1; check if the number of account is already at 5 or higher and if it is dont create the account and dont increase the count.
2: Loop through the number of account variable and print.
I added password system to it. and nice looking account num.
Code :
import java.io.*;
import java.util.Random;
public class Computer_Bank_of_India {
public static int NewRandom(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String args[])throws IOException, InterruptedException {
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
Bank myBank = new Bank();
int Option = 1, Account_Number, Account_Password, atempts = 0, Pass;
String Name;
double Balance, Money;
System.out.println("Please wait, the system is starting...");
while(Option !=5) {
Thread.sleep(4000);
System.out.println("1) Open a new bank account");
Thread.sleep(250);
System.out.println("2) Deposit to a bank account");
Thread.sleep(250);
System.out.println("3) Withdraw to bank account");
Thread.sleep(250);
System.out.println("4) Print the detailed account information including last transactions");
Thread.sleep(250);
System.out.println("5) Quit");
System.out.println();
System.out.print(" Enter Option [1-5]: ");
Option = Integer.parseInt(br.readLine());
switch(Option) {
case 1 : System.out.println("Enter a customer name :");
Name = br.readLine();
System.out.println("Enter a opening balance :");
Balance = Double.parseDouble(br.readLine());
Thread.sleep(250);
System.out.println("Creating your account....");
Thread.sleep(500);
int[] arrDetails= myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + arrDetails[0]+"\nYour password : "+ arrDetails[1]);
break;
case 2 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
System.out.println("Enter a deposit amount :");
Money = Double.parseDouble(br.readLine());
myBank.Deposit(Account_Number, Account_Password, Money);
break;
case 3 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
System.out.println("Enter a deposit amount :");
Money = Double.parseDouble(br.readLine());
myBank.Withdraw(Account_Number, Account_Password, Money);
break;
case 4 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
myBank.Transactions(Account_Number, Account_Password);
break;
case 5 : System.out.println("Please Enter your password :");
Pass = Integer.parseInt(br.readLine());
if(Pass == myBank.Password) {
System.out.println(" System shutting down.....");
Option = 5;
break;
}
else {
Thread.sleep(250);
System.out.println("You have enter a wrong password. Please try again");
Option = 0;
}
default: System.out.println("Invalid option. Please try again.");
}
}
}
static class Bank {
private int Password=2684;
private BankAccount[] accounts;
private int numOfAccounts;
public Bank() {
accounts = new BankAccount[100];
numOfAccounts = 0;
}
public int [] AddNewAccount(String Name, Double Balance) {
BankAccount b = new BankAccount(Name, Balance);
accounts[numOfAccounts] = b;
numOfAccounts++;
int Acc = b.getAccountNum()[0];
int Pass = b.getAccountNum()[1];
int[]details = {Acc, Pass};
return details;
}
public void Withdraw(int Account_Number, int pass, double Money) {
for (int i =0; i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
accounts[i].withdraw(Money);
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
public void Deposit(int Account_Number, int pass, double Money) {
for (int i =0; i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
accounts[i].deposit(Money);
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
public void Transactions(int Account_Number, int pass) {
for(int i = 0;i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a ) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(" Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
}
static class BankAccount{
private int User_Password;
private int accountNum;
private String customerName;
private double balance;
private double[] transactions;
private String[] transactionsSummary;
private int numOfTransactions;
private static int noOfAccounts=0;
public String getAccountInfo(){
return " Account number: " + accountNum + "\n Customer Name: " + customerName + "\n Balance:" + balance +"\n";
}
public String getTransactionInfo(int n) {
String transaction = transactionsSummary[n];
return transaction;
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
User_Password = NewRandom(1000, 9999);
accountNum = NewRandom(800000000, 999999999);
transactions = new double[100];
transactionsSummary = new String[100];
transactions[0] = balance;
transactionsSummary[0] = "A balance of : Rs" + Double.toString(balance) + " was deposited.";
numOfTransactions = 1;
}
public int [] getAccountNum(){
int account = accountNum;
int Pass = User_Password;
int [] details = {account, Pass};
return details;
}
public int getNumberOfTransactions() {
return numOfTransactions;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "Rs." + Double.toString(amount) + " was deposited.";
numOfTransactions++;
System.out.println(" Amount deposited successfully");
}
}
public void withdraw(double amount) {
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else {
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "Rs." + Double.toString(amount) + " was withdrawn.";
numOfTransactions++;
System.out.println(" Amount Withdrawn successfully");
}
}
}
}
}
When I update the balance of certain record in the array, using the deposit and withdraw amounts, the balance for that sepcific record changes along with the balance for the records in arrays.
How to fix it?
private String name;
private int pin;
private int account;
private static double balance;
public void setBalance(double amount)
{
balance = amount;
}
public static void deposit(double aDeposit)
{
balance = balance + aDeposit;
}
public static void withdraw(double aWithdraw)
{
if
( balance >= aWithdraw)
balance = balance - aWithdraw;
else if
( balance < aWithdraw)
System.out.println("Cannot withdarw amount.");
}
public double getBalance( )
{
return balance;
}
public boolean equal(CustomerRecord otherObject)
{
return (name.equalsIgnoreCase(otherObject.name) &&
(pin == otherObject.pin) &&
(account == otherObject.account) &&
(balance == otherObject.balance));
}
}
do{
System.out.println("Enter the name");
String aName;
Scanner keyboard = new Scanner(System.in);
aName = keyboard.nextLine();
System.out.println("Enter the pin");
int aPin;
aPin = keyboard.nextInt();
for
(int i = 0; i < index; i++) {
CustomerRecord record = anotherArray[i];
if
((record.getName().equalsIgnoreCase(aName)) && (record.getPin() == (aPin)))
{
System.out.println(record);
System.out.println("Enter the amount you wish to Deposit");
double aDeposit;
aDeposit = keyboard.nextDouble();
CustomerRecord.deposit(aDeposit);
System.out.println("Enter the amount you wish to withdraw");
double aWithdraw;
aWithdraw = keyboard.nextDouble();
CustomerRecord.withdraw(aWithdraw);
record.getBalance();
}
}
System.out.println("\nAnother Transaction? (y for yes) (n for no)");
repeat = keyboard.next().charAt(0);
}
while
(
repeat == 'y' || repeat == 'Y') ;
//Print the records on screen
{ for (int i = 0; i < index; i++)
System.out.print(anotherArray[i]);
}
You haven't shown where you define the balance field but going by the fact that you are able to access it from a static methods deposit and withdraw I would guess it is itself a static variable, say
private static double balance;
Now, what does the static mean here? If you figure that out, you will know what is the error in your program, and why changing it in one object changes it in all