Multiple User Defined Exceptions in java - java

So the scenario is to limit a user to perform three transactions a day, I wanted to finish the part where the exception is to be raised any help would be appreciated.
import java.util.Scanner;
class FundsNotAvailable extends Exception{
FundsNotAvailable(String s){
super(s);
}
}
class ExceededTransactionsLimit extends Exception{
ExceededTransactionsLimit(String s){
super(s);
}
}
class BankMethods {
String accName;
String accNumber;
Integer balance;
public Integer transactions = 0;
Scanner sc = new Scanner(System.in);
void AccOpen()
{
System.out.println("Enter Account Holder Name: ");
accName = sc.next();
System.out.println("Enter Account Number: ");
accNumber = sc.next();
System.out.println("Enter the Deposit amount: ");
balance = sc.nextInt();
}
void Deposit()
{
Integer amount;
System.out.println("Enter the Amount you wish to Deposit:");
amount = sc.nextInt();
balance = balance + amount;
}
void Withdrawal() throws FundsNotAvailable, ExceededTransactionsLimit
{
Integer amount;
System.out.println("Enter the Amount you wish to Withdraw:");
amount = sc.nextInt();
if (amount > balance)
{
throw new FundsNotAvailable("Insufficient Funds");
}
if(transactions > 3)
{
throw new ExceededTransactionsLimit("You have exceeded the daily transactions limit");
}
balance = balance - amount;
System.out.println(transactions);
}
void showBalance()
{
System.out.println("The Balance in your Account is:" + balance);
}
}
public class Bank
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BankMethods BM = new BankMethods();
BM.AccOpen();
Integer choice;
do {
System.out.println("Main Menu \n 1. Deposit \n 2. Withdraw \n 3. Show Balance \n 4. Exit");
System.out.println("Please Make A Choice:");
choice = sc.nextInt();
switch (choice) {
case 1:
BM.Deposit();
break;
case 2:
try {
BM.Withdrawal();
} catch (ExceededTransactionsLimit | FundsNotAvailable e) {
System.out.println(e.getMessage());
}
break;
case 3:
BM.showBalance();
break;
case 4:
System.out.println("Good Bye");
break;
}
}
while (choice != 4);
}
}
the condition transactions > 3 is working fine when i run it in the main class but isnt throwing an exception when i run it in the method i even tried to keep track of the transcations variable value and it kept increasing everytime i performed the withdraw operation.
Thank you (any help is appreciated)

no where in the code, value of transactions variable is getting updated.
Please add transactions++; in your Withdrawal() function and it will start working.

Related

NoSuchElementException error for ATM Machine app (Modified)

I am currently learning Java and I am trying to retain the information I learned by building a ATM machine app (I plan on adding more to it in the future).
My current issue is I would like to ask a user 'What would you like to do' repeatedly until a valid input is provided(current valid inputs are 'Withdraw' and 'Deposit').
I have a loop that will repeatedly ask the user 'Please select a valid choice' if the input is not valid. If the input is valid it will execute only once, ask 'What would you like to do', and then display a NoSuchElementException. Not sure how to fix this.
Here is my code:
App.java
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("What woul you like to do?");
String response = scanner.next().toLowerCase();
Transactions newTransaction = new Transactions();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
} else if (response.equals("deposit")) {
newTransaction.Deposit();
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}
Transactions.java
import java.util.Scanner;
public class Transactions {
private int currentBalance = 100;
public void Withdrawal() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to withdraw?");
int withdrawAmount = scanner.nextInt();
if (withdrawAmount > 0) {
if (currentBalance > 0) {
currentBalance -= withdrawAmount;
System.out.println("Amount withdrawn: $" + withdrawAmount);
System.out.println("Current Balance: $" + Balance());
if (currentBalance < 0) {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println("Can't remove 0 from account");
}
scanner.close();
}
public void Deposit() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to deposit?");
int depositAmount = scanner.nextInt();
if (depositAmount > 0) {
currentBalance += depositAmount;
Balance();
}
System.out.println("Amount deposited: $" + depositAmount);
System.out.println("Current Balance: $" + Balance());
scanner.close();
}
public int Balance() {
return currentBalance;
}
}
Error Message
NoSuchElementException
You can use a sentinel. A sentinel is a value entered that will end the iteration.
//incomplete code showing logic
int choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice");
choice = input.nextInt();
while(choice != -1){ //-1 is the sentinel, can be value you choose
//Some logic you want to do
System.out.println("Enter choice or -1 to end");
choice = input.NextInt(); //notice we input choice again here
}
Like has been said you should learn about loops. There are two types while-loop and for-loop. In this case you should youse the while-loop.
The implementation of your problem could be this.
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("What woul you like to do?");
String response;
Transactions newTransaction = new Transactions();
while (true) {
response = scanner.next().toLowerCase();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
break;
} else if (response.equals("deposit")) {
newTransaction.Deposit();
break;
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}

How to pass parameters values from one method to another one in the same class

I'm writing this code for an ATM simulator, with deposit, withdrawal and balance inquiry functionality. The code needs to be written with methods and not switch statements.
My deposit method works, but I have issues with both the withdraw and balanceInquiry methods. I would like to have checkAc_bal accessible to all methods, in order to perform calculations. I'm new on Java, and I'm trying to wrap my head on methods behaviors. Thanks so much.
...
import java.util.Scanner;
public class Main
{
public static void showMenu()
{
Scanner sc = new Scanner(System.in) ;
String input = null ;
do
{
input = showOptions(sc) ;
if(input != null)
{
switch(input.trim())
{
case "1" : deposit(sc) ;
break ;
case "2" : withdraw(sc);
break ;
case "3" : balanceInquiry() ;
break ;enter code here
case "4" : System.exit(0);
default : System.out.println("Wrong option entered. Exiting application") ;
System.exit(0);
}
}
}while(true) ;
}
public static String showOptions(Scanner sc)
{
System.out.println("********************Welcome to ATM Machine******************** ");
System.out.println("Enter Option");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance Inquiry");
System.out.println("4. Exit\n");
String input = sc.nextLine() ;
return input ;
}
public static void deposit (Scanner sc) {
int checkAc_bal = 0;
System.out.print("Enter amount to be deposited:");
int deposit;
Scanner s = new Scanner(System.in);
deposit = s.nextInt();
//int checkAc_bal = 0;
checkAc_bal = checkAc_bal + deposit;
System.out.println("Your Money has been successfully deposited");
System.out.println("Balance: " +checkAc_bal);
}
public static void withdraw (Scanner sc){
System.out.print("Enter money to be withdrawn:");
int withdraw;
Scanner s = new Scanner(System.in);
withdraw = s.nextInt();
if(withdraw<=checkAc_bal)
{
checkAc_bal = checkAc_bal - withdraw;
System.out.println("Please collect your money");
}
else
{
System.out.println("Insufficient Balance");
}
System.out.println("");
}
public static void balanceInquiry () {
System.out.println("Balance: " + checkAc_bal);
}
public static void main(String[] args) {
showMenu();
}
}
If you want your int to be accessible to other methods, you need to declare it in the scope of the whole class and not inside a method. Try declaring checkAc_bal in the Main class.
define it as a class member:
import java.util.Scanner;
public class Main
{
static int checkAc_bal = 0; //<------------------------add this
public static void showMenu()
{
Scanner sc = new Scanner(System.in) ;
String input = null ;
do
{
input = showOptions(sc) ;
if(input != null)
{
switch(input.trim())
{
case "1" : deposit(sc) ;
break ;
case "2" : withdraw(sc);
break ;
case "3" : balanceInquiry() ;
break ;enter code here
case "4" : System.exit(0);
default : System.out.println("Wrong option entered. Exiting application") ;
System.exit(0);
}
}
}while(true) ;
}
public static String showOptions(Scanner sc)
{
System.out.println("********************Welcome to ATM Machine******************** ");
System.out.println("Enter Option");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance Inquiry");
System.out.println("4. Exit\n");
String input = sc.nextLine() ;
return input ;
}
public static void deposit (Scanner sc) {
// int checkAc_bal = 0; <---------------- remove this
System.out.print("Enter amount to be deposited:");
int deposit;
Scanner s = new Scanner(System.in);
deposit = s.nextInt();
//int checkAc_bal = 0;
checkAc_bal = checkAc_bal + deposit;
System.out.println("Your Money has been successfully deposited");
System.out.println("Balance: " +checkAc_bal);
}
public static void withdraw (Scanner sc){
System.out.print("Enter money to be withdrawn:");
int withdraw;
Scanner s = new Scanner(System.in);
withdraw = s.nextInt();
if(withdraw<=checkAc_bal)
{
checkAc_bal = checkAc_bal - withdraw;
System.out.println("Please collect your money");
}
else
{
System.out.println("Insufficient Balance");
}
System.out.println("");
}
public static void balanceInquiry () {
System.out.println("Balance: " + checkAc_bal);
}
public static void main(String[] args) {
showMenu();
}
}
You have three queries, here are the answers :
Declare the variable globally to be accessible from all the methods.
Not to use switch case (U need to use if-else in that case)
How to pass parameters to methods in same class ?
I see you already did this in your code. You called other methods by parameters and received them as well.
Or frame your question well , as what exactly you need.
So here is the complete code :
import java.util.Scanner;
public class Main{
static int checkAc_bal = 0; // <---- declare on class scope
public static void showMenu() {
Scanner sc = new Scanner(System.in) ;
String input = null ;
do {
input = showOptions(sc) ;
if(input != null) {
// removed the switch-case and if-else used
if(input.trim().equals("1")) {deposit();}
else if(input.trim().equals("2")) {withdraw();}
else if(input.trim().equals("3")) {balanceInquiry();}
else if(input.trim().equals("4")) {System.exit(0);}
else {
System.out.println("Wrong option entered. Exiting application") ;
System.exit(0);
}
}
}while(true) ;
}
public static String showOptions(Scanner sc){
System.out.println("********************Welcome to ATM Machine******************** ");
System.out.println("Enter Option");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance Inquiry");
System.out.println("4. Exit\n");
String input = sc.nextLine() ;
return input ;
}
public static void deposit () {
System.out.print("Enter amount to be deposited:");
int deposit;
Scanner s = new Scanner(System.in);
deposit = s.nextInt();
checkAc_bal = checkAc_bal + deposit;
System.out.println("Your Money has been successfully deposited");
System.out.println("Balance: " +checkAc_bal);
}
public static void withdraw (){
System.out.print("Enter money to be withdrawn:");
int withdraw;
Scanner s = new Scanner(System.in);
withdraw = s.nextInt();
if(withdraw<=checkAc_bal) {
checkAc_bal = checkAc_bal - withdraw;
System.out.println("Please collect your money");
} else {
System.out.println("Insufficient Balance");
}
System.out.println("");
}
public static void balanceInquiry () {
System.out.println("Balance: " + checkAc_bal);
}
public static void main(String[] args) {
showMenu();
}
}
Output :
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
1
Input : 1
Enter amount to be deposited:100
Your Money has been successfully deposited
Balance: 100
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
1
Input : 1
Enter amount to be deposited:200
Your Money has been successfully deposited
Balance: 300
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
1
Input : 1
Enter amount to be deposited:200
Your Money has been successfully deposited
Balance: 500
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
3
Input : 3
Balance: 500
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit

Java Scanner/Input Help (input mismatch exception)

atm program. when you press a number it redirects you to an option. ex. 2 = deposit. it asks for the amount to withdraw or to press 'b' to go to the main menu. if you input the amount to deposit it works fine. if you press 'b' to get to the main menu, it will not work and send an input mismatch exception
static double balance = 0.0;
public static void deposit(double amount)
{
balance = balance + amount;
}
public static void withdraw(double amount)
{
balance = balance - amount;
}
private static void transaction()
{
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the ATM");
System.out.println("1 for balance\n2 for deposit\n3 for withdraw");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Your balance is " + balance);
transaction();
case 2:
System.out.println("Enter the amount or 'b' to go back");
if (input.nextLine() == "b")
{
transaction();
}
else
{
deposit(input.nextDouble());
System.out.println("Success!");
transaction();
}***
case 3:
if (balance >= 0)
{
System.out.println("Your balance is negative!");
}
else
{
System.out.println("Enter the amount");
withdraw(input.nextDouble());
System.out.println("Success!");
transaction();
}
default:
System.out.println("Enter a valid option");
transaction();
}
}
use .quals() instead of == for equality checking -
input.nextLine().equals("b")
Bonus suggestion:
You should not take input directly inside if() rather take the user input as String first. Then check if its b otherwise convert it to double and deposit it!
String userInput = input.next();
if (userInput.equals("b")) {
transaction();
} else {
try {
double depositAmount = Double.parseDouble(userInput);
deposit(depositAmount);
} catch (NumberFormatException ex) {
System.out.println("Invalid input");
}
}
since user some time can enter white space before or after character it is always good to have trim for user inputs.
I would suggest even to make a null check before entering the condition since else case could even work for null input.
It is always good coding practice to use equals with field that is a constant as first argument in order to avoid NullPointerException.
import java.util.Scanner;
public class Test {
static double balance = 0.0;
public static void deposit(double amount)
{
balance = balance + amount;
}
public static void withdraw(double amount)
{
balance = balance - amount;
}
private static void transaction()
{
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the ATM");
System.out.println("1 for balance\n2 for deposit\n3 for withdraw");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Your balance is " + balance);
transaction();
case 2:
System.out.println("Enter the amount or 'b' to go back");
String temp = input.nextLine().trim();
if(!temp.isEmpty()) {
if ("b".equals(temp)) // since user some time can enter white space before or after character // I would suggest even to make a null check before entering box.
{
transaction();
}
else
{
deposit(input.nextDouble());
System.out.println("Success!");
transaction();
}
}
case 3:
if (balance >= 0)
{
System.out.println("Your balance is negative!");
}
else
{
System.out.println("Enter the amount");
withdraw(input.nextDouble());
System.out.println("Success!");
transaction();
}
default:
System.out.println("Enter a valid option");
transaction();
}
}
}
Hope this was helpful.

how can i update balance after doing withdrawal and deposits(withdraw,deposit,balance inquiry) java

I have a homework in java. I am tasked to build a bank that can withdraw, deposit and inquire balance. My problem is that I couldn't get to update my balance after deposits and withdrawals... I've tried everything I could do but still cant get the logic. Can someone help add to my program... thanks
import java.util.Scanner;
public class bankJava
{
Scanner input = new Scanner(System.in);
double balance;
double amount;
public void withdraw()
{
System.out.println("Enter amount: ");
amount = input.nextInt();
balance = balance - amount;
}
public void deposit()
{
System.out.println("Enter amount: ");
amount = input.nextInt();
balance = balance + amount;
}
public void accBalance()
{
}
}
---------------------------------MAIN--------------------------------
import java.util.Scanner;
public class bankJavaTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int action;
bankJava wdraw = new bankJava();
bankJava dposit = new bankJava();
bankJava balanceInquiry = new bankJava();
bankJava amount = new bankJava();
do{
System.out.println("Choose Action: ");
System.out.println("(1) Withdraw");
System.out.println("(2) Deposit");
System.out.println("(3) Balance Inquiry");
System.out.println("(4) Exit");
action = input.nextInt();
switch(action){
//---------WITHDRAW------------//
case 1 :
System.out.println("******Withdraw******");
wdraw.withdraw();
System.out.println("***************************");
break;
//---------DEPOSIT------------//
case 2 :
System.out.println("******Deposit******");
dposit.deposit();
System.out.println("***************************");
break;
//-----------Balance Inquiry-------//
case 3 :
System.out.println("******Balance Inquiry******");
balanceInquiry.accBalance();
System.out.println("***************************");
break;
case 4 :
System.out.println("Thank you for choosing our bank!");
break;
default :
System.out.println("Invalid action.");
break;
}
}while(action != 4);
}
}
Why you are instatiating 4 different JavaBank? Doing this for each operation you will execute each method in a different object. If I understand well your question I think you could resolve your problem easily working in the same object.
import java.util.Scanner;
public class bankJavaTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int action;
bankJava myJavaBank = new bankJava(); //creating the bank
do{
System.out.println("Choose Action: ");
System.out.println("(1) Withdraw");
System.out.println("(2) Deposit");
System.out.println("(3) Balance Inquiry");
System.out.println("(4) Exit");
action = input.nextInt();
switch(action){
//---------WITHDRAW------------//
case 1 :
System.out.println("******Withdraw******");
myJavaBank.withdraw(); //withdrawing from it
System.out.println("***************************");
break;
//---------DEPOSIT------------//
case 2 :
System.out.println("******Deposit******");
myJavaBank.deposit(); //deposit from it
System.out.println("***************************");
break;
//-----------Balance Inquiry-------//
case 3 :
System.out.println("******Balance Inquiry******");
myJavaBank.accBalance();
//You don't post this method but I suppose it will refer to the same bank
System.out.println("***************************");
break;
case 4 :
System.out.println("Thank you for choosing our bank!");
break;
default :
System.out.println("Invalid action.");
break;
}
}while(action != 4);
}
}
Now should work. With your code you had 4 different bank, one only for deposit, one only for withdraw and so on. So one bank will continue to increase money, and one continue to decrease in negative.
Morover the amount parameter should not be a JavaBank parameter, bur a local variable inside each method so that it does not define a Bank.
Something like
public class bankJava
{
Scanner input = new Scanner(System.in);
double balance;
public void withdraw()
{
System.out.println("Enter amount: ");
double amount = input.nextInt();
balance = balance - amount;
}
public void deposit()
{
System.out.println("Enter amount: ");
double amount = input.nextInt();
balance = balance + amount;
}
I also suggest to change the input.nextInt() with input.nextDouble() so that you create the amount as a double.
If you don't see the Balance Inquiry is because obviously you have the accBalance() method blank. Edit it like this:
public void accBalance(){
System.out.println("Your balance is: "+this.balance);
}
import java.util.Scanner;
public class BankJava {
double balance = 0;
double amount;
public void withdraw(int amount) {
balance = balance - amount;
}
public void deposit(int amount) {
balance = balance + amount;
}
public double showBalance() {
return balance;
}
public static void main(String[] args) {
BankJava bank = new BankJava();
Scanner input = new Scanner(System.in);
int action;
int amount;
do{
System.out.println("Choose Action: ");
System.out.println("(1) Withdraw");
System.out.println("(2) Deposit");
System.out.println("(3) Balance Inquiry");
System.out.println("(4) Exit");
action = input.nextInt();
switch(action){
//---------WITHDRAW------------//
case 1 :
System.out.println("******Withdraw******");
System.out.println("enter amount:");
amount = input.nextInt();
bank.withdraw(amount);
System.out.println("***************************");
System.out.println("Your balance is now: " + bank.showBalance());
break;
//---------DEPOSIT------------//
case 2 :
System.out.println("******Deposit******");
System.out.println("enter amount:");
amount = input.nextInt();
bank.deposit(amount);
System.out.println("***************************");
System.out.println("Your balance is now: " + bank.showBalance());
break;
//-----------Balance Inquiry-------//
case 3 :
System.out.println("******Balance Inquiry******");
System.out.println("Your balance is: " + bank.showBalance());
System.out.println("***************************");
break;
case 4 :
System.out.println("Thank you for choosing our bank!");
break;
default :
System.out.println("Invalid action.");
break;
}
}while(action != 4);
}
}
Try this code, compare with yours and figure out whats wrong, also you can ask me if you need more help

How would I have test code to test if an input has characters instead of numbers

public void deposit (double amount){
if (amount >= 0) {
balance = balance + amount;
} else {
System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
}
while (!double || !int) {
System.out.println("Invalid Input. Try again");
}
}
This is the code, I am trying to get to test whether or not a user input entered in another class file has a character other than an integer or double. I need for this piece of code to work here and with a withdraw class that I have already created underneath this one, I figured if it I can get it to work in one it will work in the other.
Thanks in advance!
Here is the code Requested:
import java.util.Scanner;
public class Bank {
double balance = 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
System.out.println("How Much would you like to deposit?");
double amount;
amount = in.nextDouble();
System.out.println("Depositing: " + amount);
account1.deposit(amount);
//balance = amount + balance;
break;
case 2:
//Withdraw money
System.out.println("How much would you like to withdraw?");
amount = in.nextDouble();
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);
}
}
And here is the entirety of the first portion of code:
public class BankAccount {
public double balance;
public int sufficientFunds = 1;
public int insufficientFunds = -1;
public BankAccount(){
balance = 0;
}
public BankAccount (double initialBalance){
balance = initialBalance;
}
public void deposit (double amount){
if (amount >= 0) {
balance = balance + amount;
} else {
System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
}
while (!double || !int) {
System.out.println("Invalid Input. Try again");
}
}
public double withdraw (double amount){
balance = balance - amount;
if (balance == amount){
return sufficientFunds;
}else if (balance > amount){
return sufficientFunds;
}else if (balance < amount){
System.out.println("INSUFFICENT FUNDS");
return insufficientFunds;
}
return amount;
}
public double getBalance(){
return balance;
}
}
Java is a strongly typed language, so there is no chance that the amount variable could contain anything other than a double, which is a number.
Use this for bank
import java.util.Scanner;
public class Bank {
double balance = 0;
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
public void thisShouldBeAMethod(){
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();
String regex = "[0-9]+";
String input = in.next();
if(input.matches(regex)){
userChoice = Integer.parseInt(input);
switch (userChoice) {
case 1:
// Deposit Money
System.out.println("How Much would you like to deposit?");
double amount;
amount = in.nextDouble();
System.out.println("Depositing: " + amount);
account1.deposit(amount);
// balance = amount + balance;
break;
case 2:
// Withdraw money
System.out.println("How much would you like to withdraw?");
amount = in.nextDouble();
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;
}
else{
System.out.println("Invalid Input. Try again");
}
} while (!quit);
}
}
update this in BankAccount
public void deposit (double amount){
if (amount >= 0) {
balance = balance + amount;
} else {
System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
}
// while (!double || !int) {
// System.out.println("Invalid Input. Try again");
// }
}
And test
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
Bank bank = new Bank();
bank.thisShouldBeAMethod();
}
}
Ok, so when accepting the input for amount, surround it with a try-catch block so that instead of simply
amount = in.nextDouble();
you'll get
try{
amount = in.nextDouble();
}catch(InputMismatchException ime){
//What to do if this is not a numerical value
}
Additionally you'll want to wrap that in a do-while loop so that the program asks again until a valid input is accepted:
boolean inputInvalid;
double amount;
do{
System.out.println("How Much would you like to deposit?");
try{
amount = in.nextDouble();
inputInvalid = false;
}catch(InputMismatchException ime){
//What to do if this is not a numerical value
inputInvalid = true;
}
}while(inputInvalid);
Edit: due to the in.nextDouble(), the program may be continuously trying to read the \n in the buffer (which is when the user presses Enter). To avoid this, right after initializing the Scanner object (or first thing in a method if it's a class variable), add
in.useDelimiter("\n");
To the Java to end the input at that and ignore the newline character.

Categories