My Code won't stop printing in a loop - java

import java.util.InputMismatchException;
import java.util.Scanner;
public class Bank
{
double balance = 0;
double amount = 0;
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
{
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
//Deposit Money
boolean inputInvalid = false;
do {
System.out.println("How Much would you like to deposit?");
try {
in.useDelimiter("\n");
amount = in.nextDouble();
inputInvalid = false;
} catch(InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
inputInvalid = true;
}
} while (inputInvalid);
System.out.println("Depositing: " + amount);
account1.deposit(amount);
//balance = amount + balance;
break;
case 2:
//Withdraw money
boolean InvalidInput = false;
do {
System.out.println("How Much would you like to withdraw?");
try {
in.useDelimiter("\n");
amount = in.nextDouble();
InvalidInput = false;
} catch(InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
InvalidInput = true;
}
} while (InvalidInput);
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
//balance = balance - amount;
break;
case 3:
//check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println(account1.balance);
break;
case 0:
System.out.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
} while
(!quit);
}
}
My code otherwise works fine but I can't seem to figure out why it won't stop repeatedly printing my error message for the user. If someone can point out my error for me that would be fantastic. I did have this same code in another question however they fixed my problem that I had in the last question and were unable to answer the problem that arose here.

You need to remove or comment out the following line from your code :
in.useDelimiter("\n");
This is causing the the character "\n" to be passed to the amount = in.nextDouble(), which in turn causes the InputMismatchException to be thrown , thus resulting in an infinite loop.
UPDATE : Working code and the Sample output for your convinience:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Bank {
public static void main(String[] args) {
double balance = 0;
double amount = 0;
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
{
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
System.out.print("User Input :");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
// Deposit Money
boolean inputInvalid = false;
do {
System.out.println("How Much would you like to deposit?");
try {
// in.useDelimiter("\n");
amount = in.nextDouble();
inputInvalid = false;
} catch (InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
inputInvalid = true;
}
} while (inputInvalid);
System.out.println("Depositing: " + amount);
account1.deposit(amount);
// balance = amount + balance;
break;
case 2:
// Withdraw money
boolean InvalidInput = false;
do {
System.out.println("How Much would you like to withdraw?");
try {
// in.useDelimiter("\n");
amount = in.nextDouble();
InvalidInput = false;
} catch (InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
InvalidInput = true;
}
} while (InvalidInput);
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
// balance = balance - amount;
break;
case 3:
// check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println("Available Balance is : " + account1.getBalance());
break;
case 0:
System.out.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
} while (!quit);
}
}
}
Sample Output :
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :1
How Much would you like to deposit?
100
Depositing: 100.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :25
Error: Choice not recognized please choose again.
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :2
How Much would you like to withdraw?
25
Withdrawing: 25.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :3
Checking Balance.
Available Balance is : 75.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :0
Thanks for Using BankAccount Banking System!

Try this
String value = in.nextLine();
String v="";
for(int i=0;i<value.length();i++)
if(value.charAt(i)!='\n')
v+=value.charAt(i);
double amount =-1;
if(v!=null)
amount = Double.parseDouble(v);

Related

How do I loop for only specific "case" in switch/case?

I used switch/case to print yearly earnings depending on the bank account the user choose and I want to make this program, whenever the user enters inappropriate input, print "inappropriate input" message and let the user to re-enter the bank account they want to choose. But, currently my code only prints "inappropriate input" message. How can I fix it?
public static void main(String[] args) throws Exception
{
//initialize variables
String bank = "";
double money;
//asks the user to type the amount of money
Scanner myinput = new Scanner (System.in);
System.out.print("Please enter the amount of money you want in the bank: ");
//if the input is inappropriate, ensures the user to type the correct input
while (true) {
try {
money = myinput.nextDouble();
break;
} catch (Exception e) {
System.out.println("This is inappropriate. Please enter the amount of money you want in the bank: ");
myinput.nextLine();
}
}
//asks user to type the type of account they want
System.out.println("Please enter the type of account you want: ");
bank = myinput.next();
//print yearly earnings depending on the type of account that user chose
switch (bank) {
case "A" , "C": //if the user enters A or C, 1.5% of money will be yearly earnings
System.out.println("You can make $" + (Math.round((0.015 * money)*100)) / 100.0);
break;
case "B": //if the user enters A or C, 2% of money will be yearly earnings
System.out.println("You can make $" + (Math.round((0.02 * money)*100)) / 100.0);
break;
case "X": //if the user enters A or C, 5% of money will be yearly earnings
System.out.println("You can make $" + (Math.round((0.05 * money)*100)) / 100.0);
break;
default:
System.out.println ("This is inappropriate input. Please enter the type of account you want");
bank = myinput.nextLine();
}
//closing scanner
myinput.close();
}//end main
You can have one boolean variable for getting out of while-loop.
Flag is set to false in switch/case because while(false) wont iterate further.
boolean flag = true;
while(flag){
switch(bank){
case "A","C":
System.out.println("You can make $" + (Math.round((0.015 * money)*100)) / 100.0);
flag = false; //put this in all case.
break;
...
}
}
package com.javatutorial;
import java.util.Scanner;
class Main{
public static void main(String[] args) throws Exception
{
String bank = "";
double money = 0;
boolean valid = false;
Scanner myinput = new Scanner (System.in);
System.out.print("Please enter the amount of money you want in the bank: ");
while (true) {
try {
money = myinput.nextDouble();
break;
} catch (Exception e) {
System.out.println("This is inappropriate. Please enter the amount of money you want in the bank: ");
myinput.next();
}
}
do {
System.out.println("Please enter the type of account you want: ");
bank = myinput.next();
switch (bank) {
case "A":
case "C":
System.out.println("You can make $" + (Math.round((0.015 * money) * 100)) / 100.0);
valid = true;
break;
case "B":
System.out.println("You can make $" + (Math.round((0.02 * money) * 100)) / 100.0);
valid = true;
break;
case "X":
System.out.println("You can make $" + (Math.round((0.05 * money) * 100)) / 100.0);
valid = true;
break;
default:
System.out.println("This is inappropriate input. Please enter the type of account you want");
}
}while( !valid);
}
}

Q: Doing multiple loops and multiple if-statements and if-else-statements | RENTAL CAR CALCULATOR PROJECT

my instructions on the project were as followed:
Instructions: Use a sentinel value loop. To create a basic Rental Car Calculator
Ask each user for:
Type of vehicle (May use something other than strings, such as: 1 for an economy, 2 for a sedan, etc.) Days rented Calculate the (For each customer):
Rental cost, Taxes, Total Due. There are three different rental options with separate rates: Economy # 31.76, sedan # 40.32, SUV # 47.56. [Note: only whole day units to be considered (no hourly rates)].
Sales tax is = to 6% on the TOTAL.
Create summary data with:
The number of customers Total money collected. Also, Include IPO, algorithm, and desk check values (design documents).
{WHAT I HAVE GOING AND MY QUESTION(S)}
package tests;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Tester {
public static void main(String []args){
int count=0;
int days;
int cus;
int carType;
double dailyFee=0, nonTaxTotal, total,fullTotal=0;
boolean checkRunOrQuit = false, chooseTypeVehicle = false, numberOfDAysChosen = false;
Scanner in=new Scanner(System.in);
while ( !checkRunOrQuit ) {
System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
try {
cus=in.nextInt();
switch ( cus ) {
case 0: System.out.println("End of application");
System.exit(0); // This will actually end your application if the user enters 0, no need to verify later on
break;
case 1: checkRunOrQuit = true;
break;
default:
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid entry: ");
in.next();
}
}
while( !chooseTypeVehicle ) { // --> simplified comparison
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
try {
carType = in.nextInt();
chooseTypeVehicle = true;
switch ( carType ) {
case 1: dailyFee = 31.76;
break;
case 2: dailyFee = 40.32;
break;
case 3: dailyFee = 47.56;
break;
default:
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
chooseTypeVehicle = false;
break;
}
} catch (InputMismatchException ex) {
System.out.println("Answer must be a number");
in.next(); // -> you forgot this one.
}
}
while ( !numberOfDAysChosen ) {
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
} else {
nonTaxTotal = (dailyFee * days);
total = (nonTaxTotal * 1.06);
fullTotal+=total;
numberOfDAysChosen = true;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
in.next();
}
}
in.close();
System.out.println("Count of customers : " + count);
System.out.printf("total of the Day : $ %.2f", fullTotal);
}
}
How would I make this program loop back to prompting the user: "Press 1 to enter Rental Calculator or else press 0 to quit\". After the "days rented input is entered?
[Note: Once the days rented is input, I was wanting a total calculation but not a summary. However, I want the summary info when the program is exited.]

Getting IllegalStateException in my program?

Stacktrace Here
import java.util.*;
public class AccountClient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean infiniteLoop = true;
boolean invalidInput;
int id;
// Create array of different accounts
Account[] accountArray = new Account[10];
//Initialize each account array with its own unique id and a starting account balance of $100
for (int i = 0; i < accountArray.length; i++) {
accountArray[i] = new Account(i, 100);
}
do {
try {
//inner loop to detect invalid Input
do {
invalidInput = false;
System.out.print("Enter an id: ");
id = input.nextInt();
if (id < 0 || id > 9) {
System.out.println("Try again. Id not registered in system. Please enter an id between 0 and 9 (inclusive).");
invalidInput = true;
input.nextLine();
}
} while (invalidInput);
boolean exit;
do {
exit = false;
boolean notAnOption;
int choice;
do {
notAnOption = false;
System.out.print("\nMain Menu\n1: check balance\n2: withdraw\n3: deposit\n4: exit\nEnter a choice: ");
choice = input.nextInt();
if (choice < 1 || choice > 4) {
System.out.println("Sorry, " + choice + " is not an option. Please try again and enter a number between 1 and 4 (inclusive).");
notAnOption = true;
}
} while(notAnOption);
switch (choice) {
case 1: System.out.println("The balance for your account is $" + accountArray[id].getBalance());
break;
case 2: {
boolean withdrawFlag;
do {
System.out.print("Enter the amount you would like to withdraw: ");
double withdrawAmount = input.nextInt();
if (withdrawAmount > accountArray[id].getBalance()) {
System.out.println("Sorry, you only have an account balance of $" + accountArray[id].getBalance() + ". Please try again and enter a number at or below this amount.");
withdrawFlag = true;
}
else {
accountArray[id].withdraw(withdrawAmount);
System.out.println("Thank you. Your withdraw has been completed.");
withdrawFlag = false;
}
} while (withdrawFlag);
}
break;
case 3: {
System.out.print("Enter the amount you would like to deposit: ");
double depositAmount = input.nextInt();
accountArray[id].deposit(depositAmount);
System.out.println("Thank you. You have successfully deposited $" + depositAmount + " into your account.");
}
break;
case 4: {
System.out.println("returning to the login screen...\n");
exit = true;
}
break;
}
} while (exit == false);
}
catch (InputMismatchException ex) {
System.out.println("Sorry, invalid input. Please enter a number, no letters or symbols.");
}
finally {
input.close();
}
} while (infiniteLoop);
}
}
The exception code:
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1070)
at java.util.Scanner.next(Scanner.java:1465)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at playground.test.main.Main.main(Main.java:47)
Hello, I made a basic program that uses a class called account to simulate an ATM machine. I wanted to throw an exception if the user didn't type in a letter. This worked fine, however I needed to make it loop so the program didn't terminate after it threw the exception. To do this I just put the try catch in the do while loop I had previously. When I did this though, it's throwing an IllegalStateException every time I type in a letter or choose to exit an inner loop I have which takes the user back to the loop of asking them to enter their id. What is an IllegalStateException, what is causing it in my case, and how would I fix this? Thanks.
It's fairly simple, after you catch the exception the finally clause gets executed. Unfortunately you're closing the scanner within this clause and Scanner.close() closes the underlying input stream (System.in in this case).
The standard input stream System.in once closed can't be opened again.
To fix this you have to omit the finally clause and close the scanner when your program needs to terminate and not earlier.

Interest calculator not displaying results

I'm trying to finish this at the last minute for my Java class, when I run the program after it asks the user if the information is correct, it just loops back to the first question no matter what. Here's the code:
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userResponse = null;
do {
int quartersDisplayed = -1;
double startingBalance = -1,
interestRate = -1;
do {
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
} catch(NumberFormatException e) {
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try {
startingBalance = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(startingBalance <= 0) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try {
interestRate = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
System.out.println("You have entered the following amount of quarters: "
+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "
+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "
+ quarterlyEndingBalance);
System.out.println("Do you want to continue?");
userResponse = input.next();
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
} while(true);
}
}
What I am looking for as a sample output:
Enter number of quarters from 1 to 10
5
Enter the beginning principal balance greater than zero
4500
Enter the interest rate percentage without the percent sign, greater than 0 percent and less than/equal to 20%
3.5
You entered a principal balance of $4500.0 for 5 quarters at 3.5% interest.
Is this correct? (y/n)
y
Quarter Beginning Interest Ending
Number Balance Earned Balance
1 4500.00 39.38 4539.38
ect ect
Maybe what you ment to do is to restart the loop, if the input was wrong. In this case, you just need to switch the continue and the break.
The continue statement makes a loop immediately start the next iteration. You shoud either remove it by an empty statement ;, or negate the if-condition, remove the else and make it break on true. In addition, your code does nothing else, then getting the input and asking whether it is correct. And as it is written inside a do...while(true) loop, this loop will never end. So either remove that loop, or add an option to abort the process.
Your code should look something like the one below...
**Look out to the bottom, where the user is informed of the values entered and check for the changes made**. This is quite simple...
import java.util.Scanner;
public class correctstack{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userResponse = null;
do {
int quartersDisplayed = -1;
double startingBalance = -1,
interestRate = -1;
do {
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
} catch(NumberFormatException e) {
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try {
startingBalance = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(startingBalance <= 0) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try {
interestRate = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
System.out.println("You have entered the following amount of quarters: "+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
//Here, you give the user the opportunity to continue or re-enter the values. So you go like...
System.out.println("Is this info correct?");
String user_input = input.next();
if("y".equalsIgnoreCase(user_input) || "yes".equalsIgnoreCase(user_input)){
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "+ quarterlyEndingBalance);
System.out.println("\n\nDo you want to continue?");
userResponse = input.next();
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
}
else
continue;
} while(true);
}
}

Arrays and bank accounts in Java

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!
//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
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:
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();
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.
You have written the above code, but it has many mistakes. You need to learn the The basics of Java programming.
I have modified your program to perform below operations :-
Create new account.
Select existing account.
Deposit amount.
Withdraw amount.
View balance.
Delete account.
Exit.
Account.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 :
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!

Categories

Resources