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);
}
}
Related
Currently, I am working on a ATM project. I was able to make it work. However, I'm not sure what to do if the user enters an undercase letter than the uppercase letter on the switch statement. Also, should I use a while loop so the user can able to repeat the steps. Finally, I'm stuck on how to let the user exit the program whenever. Like for instance, exiting after completing their selection.
public static void main(String[] args) {
double checkingAccount = 5000;
double savingAccount = 2000;
Scanner cin = new Scanner(System.in);
//Welcoming the user!
System.out.println("=======================");
System.out.println("Welcome to SoundBank!");
System.out.println("=======================");
// Selections for the user
System.out.println("Please choose: \nA - Checking Account \nB - Savings Account");
String choice1 = cin.nextLine();
System.out.println("Please choose of the following: \nD - Deposit \nW - Withdrawal \nC - Check Balance \nE - Exit");
String choice2 = cin.nextLine();
// It's time for loops
switch (choice2) {
case "D":
// Checking Account
if (choice1.equalsIgnoreCase("A")) {
System.out.println("How much you do you want to deposit?");
double amount = cin.nextDouble();
double total1 = checkingAccount + amount;
System.out.println("You deposited " + amount);
System.out.println("You currently have: " + total1);
} else
// Saving Account
if (choice1.equalsIgnoreCase("B")) {
System.out.println("How much you do you want to deposit?");
double amount2 = cin.nextDouble();
double total2 = savingAccount + amount2;
System.out.println("You deposited " + amount2);
System.out.println("You currently have: " + total2);
}
break;
case "W":
// Checking Account
if (choice1.equalsIgnoreCase("A")) {
System.out.println("How much do you want to withdraw?");
double amount3 = cin.nextDouble();
double total3 = checkingAccount - amount3;
System.out.println("You withdrew " + amount3);
System.out.println("You currently have: " + total3);
} else
// Saving Account
if (choice1.equalsIgnoreCase("B")) {
System.out.println("How much do you want to withdraw?");
double amount4 = cin.nextDouble();
double total4 = savingAccount - amount4;
System.out.println("You withdrew " + amount4);
System.out.println("You currently have: " + total4);
}
break;
case "C":
// Checking Account
if (choice1.equalsIgnoreCase("A")) {
System.out.println("Your current balance is: " + checkingAccount);
} else
// Saving Account
if (choice1.equalsIgnoreCase("B")) {
System.out.println("Your current balance is: " + savingAccount);
}
break;
case "E":
System.out.println("You exited the program.");
break;
default:
System.out.println("Please choose a selction.");
}
}
I would just do
switch(choice2.toUpperCase())
so you don't have to worry about whether they put in upper or lowercase, but you could also do
case "D": // fall through
case "d":
to have two cases for the same block of code.
For existing the program, since it is all in the main function, you can just return
case "E":
System.out.println("You exited the program.");
return;
I'm making a java program for the system used at Luas Station to purchase tickets. The Luas is a type of train in the Ireland.
I have a few different types of tickets which involves various prices etc. After a customer selects what ticket to buy I give them an option to return to the beginning of the 'chooseTickets' to buy more tickets. At the end, the program I have assigned the value of all of the customer's desired tickets as the completePrice variable. the idea is to allow for the customer to continue adding tickets and for that variable to continuously add the prices of them to the variable until they're ready to pay. It works except when I go back to purchase for tickets and it is the same type, i.e a standard adult ticket twice. The price of 2.50 is not added to another 2.50, it is overwritten by another 2.5. Below is the code for the same:
import java.util.Scanner; //imports the scanner class to allow for user input
public class ticketPurchase {
//Adding global variables to be used by various methods
static Scanner input = new Scanner(System.in);
static String menuChoice;
static double childTicket = 1.20;
static double adultTicket = 2.50;
static double studentTicket = 1.70;
static double adultFlexi = 12.00;
static double childFlexi = 8.00;
static double studentFlexi;
static String ticketType;
static String ticketChoice;
static int adultTicketQty;
static int childTicketQty;
static int studentTicketQty;
static String destinationZone;
static double adultFinalPrice;
static double childFinalPrice;
static double studentFinalPrice;
static double flexiAdultFinalPrice;
static double flexiChildFinalPrice;
static double completePrice;
static String moreTicketChoice2 = "0";
public static void main(String[] args) {
menu(); //calling the menu method within the main method to start the process
}
public static void menu() {
if(moreTicketChoice2.equals("1")){
System.out.println("Press 2 to purchase Standard Tickets");
System.out.println("Press 3 to purchase Flexi tickets");
System.out.println("press 4 to purchase student tickets");
}
else if(moreTicketChoice2.equals("0")) {
System.out.println("Press 1 for information");
System.out.println("Press 2 to purchase Standard Tickets");
System.out.println("Press 3 to purchase Flexi tickets");
System.out.println("press 4 to purchase student tickets");
}
menuChoice = input.next(); //allowing user to choose what tickets to buy or just to see information of services
switch(menuChoice) { //switch statement to record and output information based on users input
case "1":{ //prints information regarding pricing, ticket age restrictions and support
System.out.println("The standard ticket may be a single or return ticket for an adult (16+) or a child");
System.out.println("The flexi ticket covers all journeys for one 24 hour period for either a child or an adult");
System.out.println("A single ticket's price depends on the journey length, single or return and if it is for an adult or a child");
System.out.println("a Flexi ticket for a child costs €8.00 and a Flexi ticket for an adult costs €12.00");
System.out.println("Our Customer Care telephone number for this terminal is 0830462920, please call if further support is required");
menu();
break;
}
case "2":{
ticketChoice = "standard"; //records the value of standard within the ticketChoice global variable
chooseTickets(); //initiates the choose tickets method
break;
}
case "3":{
ticketChoice = "flexi"; //record the value of Flexi within the ticketChoice global variable
chooseTickets();
break;
}
case "4":{
ticketChoice = "student";
chooseTickets();
}
case "a":{ //allows user to enter the admin interface
admin();
break;
}
default:{ //allows for user to input a value outside of the options and notify's them to try again
System.out.println("Invalid choice, please choose from 1 to 3");
break;
}
}
}
public static void chooseTickets() { //payment method to choose quantity, destination zone and final price
System.out.println("You have chosen to purchase " + ticketChoice + " ticket(s)");
if(ticketChoice.equals("student")) { //allows user to purchase student's tickets
ticketType = "student";
System.out.println("Please enter the quantity of tickets: ");
studentTicketQty = input.nextInt();
System.out.print("please enter your destination zone (1, 2, 3, 4): ");
destinationZone = input.next();
ticketChoice = "student";
studentFinalPrice = (studentTicket*studentTicketQty);
switch(destinationZone){ //adjusts price to account for the destination's zone chosen by user
case "1":{
studentFinalPrice = studentFinalPrice + (studentTicketQty*0);
break;
}
case "2":{
studentFinalPrice = studentFinalPrice + (studentTicketQty*0.50);
break;
}
case "3":{
studentFinalPrice = studentFinalPrice + (studentTicketQty*1.0);
break;
}
case "4":{
studentFinalPrice = studentFinalPrice + (studentTicketQty*1.50);
break;
}
default:{
System.out.println("you have entered an invalid choice please choose from 1 to 4");
chooseTickets();
break;
}
}
System.out.print("would you like to purchase more tickets? enter 1 if so, 2 if not: "); //allows user to purchase other tickets
moreTicketChoice2 = input.next();
if(moreTicketChoice2.equals("1")) {
menu();
}
else if(moreTicketChoice2.equals("2")){
System.out.println("you have chosen against purchasing more tickets");
payment();
}
}
else {
System.out.print("please enter 1 for children's tickets and 2 for adult's: ");
String ticketAgeGroup = input.next();
switch(ticketAgeGroup) { //allows user to choose quantity and destination based on choice of adult or child
case "2":{//case for adult tickets
System.out.println("you have chosen adults ticket");
ticketType = "adult";
System.out.print("Please enter the quantity of tickets: ");
adultTicketQty = input.nextInt();
System.out.print("please enter your destination zone (1, 2, 3, 4): ");
destinationZone = input.next();
if(ticketChoice == "flexi") { //if statement to calculate the finalPrice variable value if the ticketChoice is Flexi
flexiAdultFinalPrice = (adultFlexi*adultTicketQty);
}
else {
adultFinalPrice = (adultTicket*adultTicketQty); //else calculates the finalPrice variable value if the ticketChoice is standard
}
switch(destinationZone){ // switch statement to calculate the final price depending on the destination's zone and their extra amount.
case "1":{
adultFinalPrice = adultFinalPrice + (adultTicketQty*0);
break;
}
case "2":{
adultFinalPrice = adultFinalPrice + (adultTicketQty*.50); //calculation to add the extra amount for the destination
break;
}
case "3":{
adultFinalPrice = adultFinalPrice + (adultTicketQty*1.0);
break;
}
case "4":{
adultFinalPrice = adultFinalPrice + (adultTicketQty*1.50);
break;
}
default:{
System.out.println("you have entered an invalid choice please choose from 1 to 4");
break;
}
} //end of the switch statement
System.out.print("Would you like to purchase more tickets? enter 1 if so, 2 if not: "); //allows user to purchase other tickets
moreTicketChoice2 = input.next();
if(moreTicketChoice2.equals("1")) { //if statement to allow a customer to purchase more tickets if required
menu();
}
else {
System.out.println("you have chosen against purchasing more tickets");
payment(); //proceeds to the payment method
}
break;
}
case "1":{ //case for children's tickets
System.out.println("you have chosen children's ticket");
ticketType = "child";
System.out.println("Please enter the quantity of tickets: ");
childTicketQty = input.nextInt();
System.out.print("please enter your destination zone (1, 2, 3, 4): ");
destinationZone = input.next();
if(ticketChoice == "flexi") { //adjusts the price if user chooses the flexi option
flexiChildFinalPrice = (childFlexi*childTicketQty);
}
else {
childFinalPrice = (childTicket*childTicketQty);
}
switch(destinationZone){ //adjusts price to account for the destination's zone chosen by user
case "1":{
childFinalPrice = childFinalPrice + (childTicketQty*0);
break;
}
case "2":{
childFinalPrice = childFinalPrice + (childTicketQty*.50);
break;
}
case "3":{
childFinalPrice = childFinalPrice + (childTicketQty*1.0);
break;
}
case "4":{
childFinalPrice = childFinalPrice + (childTicketQty*1.50);
break;
}
default:{
System.out.println("you have entered an invalid choice please choose from 1 to 4");
chooseTickets();
break;
}
}
System.out.print("would you like to purchase more tickets? enter 1 if so, 2 if not: "); //allows user to purchase other tickets
moreTicketChoice2 = input.next();
if(moreTicketChoice2.equals("1")) {
menu();
}
else if(moreTicketChoice2.equals("2")){
System.out.println("you have chosen against purchasing more tickets");
payment();
}
break;
}
}
}
}
public static void payment() { //method to complete the payment process for the purchase
completePrice = adultFinalPrice + childFinalPrice + studentFinalPrice + flexiAdultFinalPrice + flexiChildFinalPrice;
System.out.println("the total due is €" + completePrice);
}
public static void printTickets() { //method to notify the customer that their tickets are printing
}
public static void admin() { //method to control the admin's interface
}
}
In this photo i want an output of 2.4 not 1.2
So, I have to make a program that acts as a basic ATM and I've encountered 2 problems:
When I test the program for invalid passwords with a related account, the program is supposed to do a loop count that gives the user a max of 3 invalid attempts before it kicks the user out but instead it prints "Invalid password" 3 times and ends the program after the first wrong password. I believe this one is a bracketing error but I'm not actually sure myself
AND
Whenever I run an operation like depositing money into the account, the program will display the new amount but it won't actually store the new value for the program. For example if I deposit $100 into account 1, it will say the new balance is $620.36, but when it loops back to the main menu and I check the new balance again and it reverts it back to the previous value, which it's not supposed to (tjis is where I think the logic error might be)
I was hoping for someone to be able to guide me in the right direction for either possible debugging solutions or a general solution of my error in coding.
This is the code:
import java.util.*;
public class ATM {
public static Scanner kbd;
private static final int MAXATTEMPTS = 3;
public static void main(String[] args) {
kbd = new Scanner(System.in);
System.out.println("Hello, user. This is an ATM.");
System.out.println("Please enter account number");
String acctNum = kbd.next();
System.out.println("Please enter password");
String pwd = kbd.next();
int attemptNumber = 0;
String res = checkID(acctNum, pwd);
do{
if (res.equals("error")){
attemptNumber++;
System.out.println("Invalid password, please try again.");
if (attemptNumber == MAXATTEMPTS){
System.out.print("Maximum Login Attempts Reached.");
System.exit(0);
}
}
else {
double balance = Double.parseDouble(res);
while(true){
int option = menu();
switch (option) {
case 1:
displayBalance(balance);
break;
case 2:
deposit(balance, balance);
break;
case 3:
withdraw(balance, balance);
break;
case 4:
System.out.println("Thank you for banking with us, have a nice day!");
System.exit(0);
}
}
}
}
while (res.equals("error"));
kbd.close();
}
/**
* Determines if acctNum is a valid account number and pwd is the
* correct password for the account.
* #param acctNum The account number to be tested
* #param pwd The possible password for the account
* #return If the account information is valid, returns the account balance
* as a string. If the account information is invalid, returns the string "error".
*/
public static String checkID(String acctNum, String pwd)
{
String result = "error";
// Strings a, b, and c contain the valid account numbers and passwords.
// For each string, the account number is listed first, followed by
// a space, followed by the password for the account, followed by a space,
// followed by the current balance.
String a = "44567-5 mypassword 520.36";
String b = "1234567-6 anotherpassword 48.20";
String c = "4321-0 betterpassword 96.74";
String acctNum1, acctNum2, acctNum3, pwd1, pwd2, pwd3, bal1, bal2, bal3;
acctNum1 = a.substring(0, a.indexOf(" "));
acctNum2 = b.substring(0, a.indexOf(" "));
acctNum3 = c.substring(0, a.indexOf(" "));
pwd1 = a.substring(a.indexOf(" ")+1, a.lastIndexOf(" "));
pwd2 = b.substring(b.indexOf(" ")+1, b.lastIndexOf(" "));
pwd3 = c.substring(c.indexOf(" ")+1, c.lastIndexOf(" "));
bal1 = a.substring(a.lastIndexOf(" " )+1);
bal2 = b.substring(a.lastIndexOf(" " )+1);
bal3 = c.substring(a.lastIndexOf(" " )+1);
if (acctNum.equals(acctNum1) && pwd.equals(pwd1)){
result = bal1;
}
if (acctNum.equals(acctNum2) && pwd.equals(pwd2)){
result = bal2;
}
if (acctNum.equals(acctNum3) && pwd.equals(pwd3)){
result = bal3;
}
return result;
}
/**
*/
public static int menu(){
boolean invalidInput = true;
do {
System.out.println("Please select from the following options:");
System.out.printf("1. Display Balance \n");
System.out.printf("2. Deposit \n");
System.out.printf("3. Withdraw \n");
System.out.printf("4. Log Out \n");
int choice = kbd.nextInt();
if (choice == 1){
return 1;
}
else {
if (choice == 2){
return 2;
}
else{
if (choice == 3){
return 3;
}
if (choice == 4) {
return 4;
}
}
}
}
while(invalidInput);
return 0;
}
/**
*
* #param accBalance given account balance for Account
* #param depoAmnt amount going to be added to accBalance
* #return double that will show updated balance
*/
public static double deposit(double accBalance, double depoAmnt){
System.out.println("How much would you like to deposit");
depoAmnt = kbd.nextDouble();
double newBalance = accBalance + depoAmnt;
System.out.println("Your new balance is: " + newBalance);
return newBalance;
}
/**
*
* #param accBalance amount of money in account
* #return displays amount of money in account
*/
public static void displayBalance(double accBalance){
System.out.printf("\nYour current balancre is $%.2f\n", accBalance);
}
/**
*
* #param accBalance given account balance for account
* #param withdraw amount to be taken out of account
* #return if withdraw !> accBalance, then it will be subtracted from it and resultant amount will be displayed
*/
public static double withdraw(double accBalance, double withdraw){
System.out.println("How much would you like to withdraw?");
withdraw = kbd.nextDouble();
if (accBalance < withdraw){
System.out.printf("Cannot withdraw more than balance" + "\nYour current balance is: " + accBalance + "\n");
return accBalance;
}
else {
double newBalance = accBalance - withdraw;
System.out.println("Your new balance is: " + newBalance);
return newBalance;
}
}
}
Well first of all your while loop will only execute if the result of the ID check is "error". You need to change the condition of the loop to 'true' so it will run regardless, as this is the main event loop:
do {
if (res.equals("error")){
attemptNumber++;
System.out.println("Invalid password, please try again.");
if (attemptNumber == MAXATTEMPTS){
System.out.print("Maximum Login Attempts Reached.");
System.exit(0);
}
}
else {
double balance = Double.parseDouble(res);
while(true){
int option = menu();
switch (option) {
case 1:
displayBalance(balance);
break;
case 2:
deposit(balance, balance);
break;
case 3:
withdraw(balance, balance);
break;
case 4:
System.out.println("Thank you for banking with us, have a nice day!");
System.exit(0);
}
}
}
}
while (true);
Hi I needed help with doing a calculation in this right here. On the line where it has single, i want to add the number to the calculation but it just adds it as if im just writing the number itself in a sentence. How do i add it as if its a calculation, im very stuck and need help. (Its the last line of code). I also wanted to know how i can limit the amount of letters a user can input, since i only want them to either enter 's' or 'm'. How can i limit them to only these two so they dont use a letter like 'g' for example, since that wont work.
import java.util.Scanner;
public class FedTaxRate
{
public static void main(String[] args)
{
String maritalStatus;
double income;
int single = 32000;
int married = 64000;
Scanner status = new Scanner(System.in);
System.out.println ("Please enter your marital status: ");
maritalStatus = status.next();
Scanner amount = new Scanner(System.in);
System.out.print ("Please enter your income: ");
income = amount.nextDouble();
if (maritalStatus.equals("s") && income <= 32000 )
{
System.out.println ("The tax is " + income * 0.10 + ".");
}
else if (maritalStatus.equals("s") && income > 32000)
{
System.out.println ("The tax is " + (income - 32000) * 0.25 + single + ".");
}
}
}
To answer your second question about limiting the input, you can try using a switch case statement. The default allows you to write code for the case when maritalStatus is not equal to either "s" or "m". You can also create a do-while loop to keep asking for input until maritalStatus is equal to either "s" or "m".
Scanner status = new Scanner(System.in);
String maritalStatus = status.nextLine();
do {
System.out.println("Enter your marital status.")
switch (maritalStatus) {
case "s":
// your code here
break;
case "m":
// your code here
break;
default:
// here you specify what happens when maritalStatus is not "s" or "m"
System.out.println("Try again.");
break;
}
// loop while maritalStatus is not equal to "s" or "m"
} while (!("s".equalsIgnoreCase(maritalStatus)) &&
!("m".equalsIgnoreCase(maritalStatus)));
You only need one Scanner. You can use an else with your income test. I would suggest you calculate the tax once, and then display it with formatted IO. Something like,
public static void main(String[] args) {
int single = 32000;
int married = 64000;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your marital status: ");
String maritalStatus = sc.next();
System.out.print("Please enter your income: ");
double income = sc.nextDouble();
double tax;
if ("s".equalsIgnoreCase(maritalStatus)) {
if (income <= single) {
tax = income * 0.10;
} else {
tax = (income - single) * 0.25 + single;
}
} else {
if (income <= married) {
tax = income * 0.10;
} else {
tax = (income - married) * 0.25 + married;
}
}
System.out.printf("The tax is %.2f.%n", tax);
}
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);