How to make the switch statement more accurate? - java

We were ask to make a program using the switch statement..
Here is my code:
double price = 0, totalPrice;
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
default:
System.out.println("ERROR: Invalid number!");
break;
}
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
So basically, the user will input a certain number and it will have different prices... inside the switch statements.
but if the user inputs a wrong number, it will display an error message and i dont want the user to enter the quantity which will be executed after the switch statement.
we are not allowed to use any methods or functions and i dont want to code repeatedly like this:
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
break;
case 2:
price = 410.00;
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
break;
default:
System.out.println("ERROR: Invalid number!");
break;
}
is there any other way not to use if else, methods, functions or coding repeatedly?
ANY HELP WILL BE APPRECIATED.

You can use a boolean flag and make it false if invalid option is selected.
Then only ask user further if flag is true.
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
boolean flag = true;
switch (optionNumber) {
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
default:
flag = false;
System.out.println("ERROR: Invalid number!");
break;
}
if (flag) {
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
}

Use as this:
while(!valid option)
//do this stuff
Use a flag and set it to true if the number entered is valid, so it will go to your next instruction; else ask again for input.

Throw an exception
default:
throw new InvalidArgumentException("Invalid number!");
See also InvalidArgumentException vs UnexpectedValueException

You could just remove default from the switch statement and check to see if the price is equal to 0 after the switch statement
double price = 0, totalPrice;
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
}
if (price == 0)
{
System.out.println("ERROR: Invalid number!");
}
else
{
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
}
This keeps you from adding unnecessary variables (like a boolean flag) when you already have one (price) with a default value of 0 that you can check against.

Related

Variables aren't getting updated with the proper values

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

Combining multiple switch variables into one string

I am to create a program that shows the full receipt (plus all the items included.) However, when two of the same items are selected the output is:
4 Combo price
5 Combo price
Instead of:
9 Combo price
Is it possible to merge the two same switch cases? I've tried a counter and yet it still doesn't work. I don't know what other logic to put behind this.
import java.text.NumberFormat;
import java.util.Scanner;
public class Menu {
public static void main(String args []){
final double COFFEE= 1.8, SOFTDRINK = 2.0;
final double STARTER= 4.0, DESSERT= 3.5;
final double MAIN= 8.0;
final double COMBO1 = 11.0, COMBO2= 11.5, COMBO3 = 15.0;
double sum=0;
int item = 0, quantity=0;
int freeSoftDrink=0, freeCoffee=0;
String order="";
char decide= 'N';
boolean quit= false;
Scanner sc = new Scanner (System.in);
NumberFormat format= NumberFormat.getInstance();
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(2);
do{
System.out.println("------------------ MENU ------------------");
System.out.println("ITEM"+"\t\t\t\tPRICE");
System.out.println("1.Coffee"+"\t\t\t"+"RM1.80");
System.out.println("2.Soft Drink"+"\t\t\t"+"RM2.00");
System.out.println("3.Dessert"+"\t\t\t"+"RM3.50");
System.out.println("4.Starter"+"\t\t\t"+"RM4.00");
System.out.println("5.Main Course"+"\t\t\t"+"RM8.00");
System.out.println("6.Main+Dessert"+"\t\t\t"+"RM11.00");
System.out.println("7.Main+Starter"+"\t\t\t"+"RM11.50");
System.out.println("8.Combo(Main+Starter+Dessert)"+"\t"+"RM15.00");
System.out.println("-----------------------------------------");
System.out.print("Select an item: ");
item = sc.nextInt();
if ((item<=8) && (item>=1)){
System.out.print("Enter quantity (1-50): ");
quantity = sc.nextInt();
}
while (((quantity<=0) || (quantity>=51)) && ((item<=8) && (item>=1)))
{
System.out.print("Invalid. Please re-enter quantity: ");
quantity = sc.nextInt();
}//end while
switch(item){
case 1:
System.out.println("You've ordered: "+quantity+" Coffee.\n");
sum=sum+(quantity*COFFEE);
order=order.concat(quantity +" Coffee\t\t\t"+"RM"
+format.format(quantity*COFFEE)+"\n");
break;
case 2:
System.out.println("You've ordered: "+quantity+" Soft Drink.\n");
sum=sum+(quantity*SOFTDRINK);
order=order.concat(quantity+" Soft Drink\t\t\t"+"RM"
+format.format(quantity*SOFTDRINK)+"\n");
break;
case 3:
System.out.println("You've ordered: "+quantity+" Dessert.\n");
sum=sum+(quantity*DESSERT);
order=order.concat(quantity+ " Dessert\t\t\t" +"RM"
+format.format(quantity*DESSERT)+"\n");
break;
case 4:
System.out.println("You've ordered: "+quantity+" Starter.\n");
sum=sum+(quantity*STARTER);
order=order.concat(quantity+" Starter\t\t\t"
+"RM"+format.format(quantity*STARTER)+"\n");
break;
case 5:
System.out.println("You've ordered: "+quantity+" Main.\n");
sum=sum+(quantity*MAIN);
order=order.concat(quantity+" Main\t\t\t\t" + "RM"
+format.format(quantity*MAIN)+"\n");
break;
case 6:
System.out.println("You've ordered: "+quantity+" Main+Dessert.\n");
sum=sum+(quantity*COMBO1);
order=order.concat(quantity+" Main+Dessert\t\t\t"
+"RM"+format.format(quantity*COMBO1)+"\n");
freeCoffee = freeCoffee + quantity;
break;
case 7:
System.out.println("You've ordered: "+quantity+" Main+Starter.\n");
sum=sum+(quantity*COMBO2);
order=order.concat(quantity+" Main+Starter\t\t\t"+"RM"
+format.format(quantity*COMBO2)+"\n");
freeSoftDrink = freeSoftDrink + quantity;
break;
case 8:
System.out.println("You've ordered: "+ quantity+" Combo.\n");
sum=sum+(quantity*COMBO3);
order=order.concat(quantity+" Combo"+" \t\t\t"
+"RM"+format.format(quantity*COMBO3)+"\n");
freeSoftDrink = freeSoftDrink + quantity;
freeCoffee = freeCoffee + quantity;
break;
default:
System.out.println("Invalid item.");
}//end switch
System.out.println("Do you want anything else? [Y/N]");
decide= sc.next().charAt(0);
System.out.println("");
while ((decide!='N' && decide!='n') && (decide!='Y' && decide!='y')){
System.out.print("Invalid. Try again: ");
decide=sc.next().charAt(0);
System.out.println("");
}
if (decide=='N'|| decide =='n'){
quit=true;
}
}//end do
while(!quit);
System.out.println();
System.out.println("Orders");
System.out.println("--------------------------------------------");
System.out.print(order);
if (freeCoffee<=0){
System.out.print("");
}
else {
System.out.println("*free "+ freeCoffee + " coffee.");
}
if (freeCoffee<=0){
System.out.print("");
}
else{
System.out.println("*free "+ freeSoftDrink + " soft drinks.");
}
System.out.println("--------------------------------------------");
System.out.println ("Your total bill\t\t\tRM"+ format.format(sum));
System.out.println("--------------------------------------------");
}//end main
}//end class
The specific line that is causing the issue is:
order=order.concat(quantity+"Main+Dessert\t\t\t"+"RM"+format.format(quantity*COMBO1)+"\n");
Everytime a new COMBO comes in, it appends to the string instead of adding to COMBO cost if one exists already.
A possible fix that I can think of is that you store the state of each item in a HashMap. So your case statement will look something like this:
Map<String, Integer> orderMap = new HashMap<>();
case 6:
System.out.println("You've ordered: "+quantity+" Main+Dessert.\n");
sum=sum+(quantity*COMBO1);
orderMap.containsKey("Combo")
? orderMap.put("Combo", orderMap.get("Combo") + sum) // if the key already exists then we add to the sum otherwise we create a new entry.
: orderpMap.put("Combo", sum);
freeCoffee = freeCoffee + quantity;
break;
And then you can collect all the order values and print them in the receipt:
orderMap.entrySet().forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue);
which will print something like:
Starter: 2
Combo: 9

switch statement with sentinel loop

I am having some trouble getting my sum function to work. I am trying to create a program that asks for a product number and a quantity using switch structure and a sentinel loop. It will run until 0 is entered. It should calculate the total number of products entered and the total value of all products entered. The quantity works just fine. It's the total value that will only work for the 1st product entered. I cannot get the sum for total to keep adding until 0 is pressed. Any help would be greatly appreciated!!
import java.util.Scanner;
public class Mailorder {
public static void main(String[] args) {
//create a scanner
Scanner input = new Scanner(System.in);
//declare variables
double product1 = 3.75;
double product2 = 5.95;
double product3 = 8.75;
double product4 = 6.92;
double product5 = 8.75;
double product6 = 7.87;
double total = 0.00;
//read in product #
System.out.print("Enter a product number: ");
int product = input.nextInt();
//read in quantity sold
System.out.print("Enter quantity sold for 1 day: ");
int quantity = input.nextInt();
//switch case
switch (product)
{
case 1: total = product1 * quantity; break;
case 2: total = product2 * quantity; break;
case 3: total = product3 * quantity; break;
case 4: total = product4 * quantity; break;
case 5: total = product5 * quantity; break;
case 6: total = product6 * quantity; break;
default: System.out.println("ERROR: Invalid product number");
}
//keep reading data until the input is 0
int sum1 = 0;
while (quantity != 0) {
sum1 += quantity;
int sum2 = 0;
while (total != 0) {
sum2 +=total;
}
//read the next data
System.out.print("Enter a product number: ");
product = input.nextInt();
System.out.print("Enter quantity sold for 1 day: ");
quantity = input.nextInt();
}
//print results
System.out.println("The total number of products sold last week " + sum1);
System.out.println("The total retail value of all products sold last week " + sum2);
}
}
There are a couple scoping issues here.
First, you have placed your switch statement outside of your loop. You should place it inside your loop.
Second, there is a scoping problem with sum2. It is declared inside your sentinel loop, but referenced outside. I'm not sure why you have a nested loop adding to sum2. Here is the code with these issues resolved:
public class Mailorder {
public static void main(String[] args) {
//create a scanner
Scanner input = new Scanner(System.in);
//declare variables
double product1 = 3.75;
double product2 = 5.95;
double product3 = 8.75;
double product4 = 6.92;
double product5 = 8.75;
double product6 = 7.87;
//read in product #
System.out.print("Enter a product number: ");
int product = input.nextInt();
//read in quantity sold
System.out.print("Enter quantity sold for 1 day: ");
int quantity = input.nextInt();
//keep reading data until the input is 0
int sum1 = 0;
int sum2 = 0;
while (quantity != 0) {
sum1 += quantity;
double total = 0.00;
//switch case
switch (product)
{
case 1: total += product1 * quantity; break;
case 2: total += product2 * quantity; break;
case 3: total += product3 * quantity; break;
case 4: total += product4 * quantity; break;
case 5: total += product5 * quantity; break;
case 6: total += product6 * quantity; break;
default: System.out.println("ERROR: Invalid product number");
}
sum2 += total;
//read the next data
System.out.print("Enter a product number: ");
product = input.nextInt();
System.out.print("Enter quantity sold for 1 day: ");
quantity = input.nextInt();
}
//print results
System.out.println("The total number of products sold last week " + sum1);
System.out.println("The total retail value of all products sold last week " + sum2);
}
}

Breaking a while loop by case in Java

I need to issue break a while loop if a case is matched in a switch statement. The case is as follows: if a user enters either a number less than zero or anything greater than five. I have the switch working most of my cost except the two exceptions Ive mentioned. Here is my code:
import java.util.Scanner;
public class Product
{
public static void main(String args[])
{
int cntr = 0;
int product = 0;
int units = 0;
double totalcost = 0;
Scanner MK = new Scanner(System.in);
cntr=0;
while (cntr >= 0 && cntr <=5)
{
System.out.println("Enter Product no.(1-5) or -1 to Quit");
product = MK.nextInt();
switch(product) {
case 1:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 2.98;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 2:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 4.50;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 3:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 9.98;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 4:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 4.49;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 5:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 6.87;
totalcost = totalcost + (cost*product);
System.out.println("Current total cost: " + totalcost);
cntr++;
}
case 6:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
//product = MK.nextInt();
//double cost = 2.98;
//totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
//cntr++;
}
break;
}
System.out.println("Total cost-->" +totalcost);
}
}
}
If anyone can point me in the right direction on how to stop my program when anything less than zero or greater than 5 is entered I would really appreciate it.
A couple of options:
Use a flag that you set when you want the loop to end (in your default or -1 clause), or
Use a labelled statement and a directed break in your default (or -1) clause
In this specific situation where you said you want the entire program to end, you could use System.exit
Here's more about option 2:
label: while (...) { // <== Labelled statement
switch (...) {
case ...:
// ...
break; // <=== Normal (undirected) break, just exits what
// it's in (switch in this case)
// ...
default:
break label; // <=== Directed break, exits loop
}
}
It's also handy for nested loops.
Side note: There's no need for the { and } you have surrounding the statements in your case clauses. The code for case continues until the break. (Yes, it's a bit different from other statements.)
Side note 2: You've said Enter Product no.(1-5) or -1 to Quit in your prompt, but you have cases for the values 1 to 6 (inclusive). You probably meant Enter Product no.(1-**6**) or -1 to Quit.

My Code won't stop printing in a loop

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);

Categories

Resources