(JAVA) do while loop for my vending machine - java

this project i use do while loop with switch case to check the input case is not match or not. i run the code but the result not what i wanted. what i expect is if the user type the wrong case, the do while loop will loop back to the input where user need to enter the case.
here is the code
package vending.machine;
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
import static vending.machine.adddrinks.drinksList;
public class VendingMachine {
public static void main (String []args){
Scanner sc= new Scanner(System.in);
double money;
double total;
double balance;
do{
System.out.println("\nPlease insert money:");
money = sc.nextDouble();
if(money < 1.2){
System.out.println("Not enough money");
}
}while(money < 1.2);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
System.out.print("Select: 1 or 2 or 3 or 4\n");
int select=sc.nextInt();
do{
switch(select){
case 1:{
total = adddrinks.drinksList.get(0).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 2:{
total = adddrinks.drinksList.get(1).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 3:{
total = adddrinks.drinksList.get(2).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 4:{
total = adddrinks.drinksList.get(3).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
default:{
System.out.println("Invalid");
break;
}
}
}while(select<5);
}
}
here is the result
enter image description here

From what I understood from your code. When you are giving the input as 5 it is giving invalid.
After that it will go to the while statement and check the condition there. If you are inside the switch case and select any random case It will show you invalid. After that depending upon the number that you have entered.
If the number is less than 5, It will again go to switch case.
As it doesn't make sense as If you continue to provide correct input to it. The code will continue to execute making the balance going in the negative. this condition should be changed to
while(balance>1.2)
assuming that it is minimum amount that is necessary to buy a drink. This will check the condition after every drink and will hopefully do what you were hoping.
On side Note : Make your code modular.

You need to loop over your input, i was so free to improve your code a bit (sorry I do not like repetations):
private static void main10(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
int select = 0;
double balance = 0;
boolean running = true;
while (running) {
if (sc.hasNextInt()) {
select = sc.nextInt();
if (0 < select && select <= adddrinks.drinksList.size()) {
double price = adddrinks.drinksList.get(select - 1).getdrinkPrice();
if (balance < price) {
System.out.println("Not enough money, " + select + " costs " + price);
} else {
balance -= price;
System.out.println("You choosed " + select + " , you will find it in the dispenser");
}
} else {
System.out.println("Invalid input, please retry");
}
} else if (sc.hasNextDouble()) {
balance += sc.nextDouble();
} else {
String input = sc.next();
if (input == "q") {
running = false;
if (0 < balance)
System.out.println("please don't forget your change with amount of: " + balance);
System.out.println("Have a nice day, happy to see you again");
break;
} else if (input == "h") {
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
} else {
System.out.println("Invalid input, please retry");
}
}
System.out.println("Your balance is: " + balance);
System.out.println(
"please chouce your product (e.g 2), enter coins (e.g 2.0), click on 'h' to show product list or click on 'q' to get your change");
}
}

Related

Basic Menu with Cases

I am creating a basic banking app that tracks a user's bank account activities, and I cannot seem to figure out why when I run my code that it is simply running what I have set for the "default" case; so even when I press 1,2,3, or 4, the console states, "Error -- Please choose a valid option."
Thanks in advance!
package Account;
import java.util.Scanner;
public class Account extends Bank {
int Balance;
int Previoustransaction;
int amount;
int amount2;
String Name;
String ID;
Account(String Name,String ID){
}
void deposit(int amount) {
if (amount != 0) {
Balance+=amount;
Previoustransaction=amount;
}
}
void withdraw(int amount) {
if(amount!=0) {
Balance-=amount;
Previoustransaction = -amount;
}
}
void getPrevioustransaction() {
if(Previoustransaction > 0) {
System.out.println("Deposited:" + Previoustransaction);
}
else if(Previoustransaction<0) {
System.out.println("Withdrawn:" + Math.abs(Previoustransaction));
} else {
System.out.println("No transaction occurred.");
}
}
void Menu() {
int choice = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome," + Name + ".");
System.out.println("Your account number is" + ID);
System.out.println("What would you like to do?");
System.out.println("1.Check balance.");
System.out.println("2. Make a deposit.");
System.out.println("3. Make a withrawl.");
System.out.println("4. Show last transaction.");
System.out.println("0. Exit.");
do {
System.out.println("Choose an option.");
choice = scan.nextInt();
System.out.println();
switch(choice) {
case'1':
System.out.println("Balance = $" + Balance);
System.out.println();
break;
case'2':
System.out.println("Enter an amount to deposit.");
int amount = scan.nextInt();
deposit (amount);
System.out.println();
break;
case'3':
System.out.println("Enter an amount to withdrawl.");
int amount2 = scan.nextInt();
withdraw(amount2);
break;
case '4':
getPrevioustransaction();
break;
case '0':
break;
default:
System.out.println("Error -- Please choose a valid option.");
}
} while (choice != 0);
System.out.println("Thank you for using the Bank Account Tracker!");
scan.close();
}
{
}
{
}
}
The reason your program isn't working as you expect is that:
you are prompting for user input
capturing that input as a numeric value; specifically, primitive data type int
comparing that int input against various character values – that is, values of primitive data type ch (such as '1')
Here's a paired down version of what you're doing:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case '1':
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
Here's that same block, but instead of case '1' (which matches on a single character value), I changed it to case 1 (which matches on an integer value):
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1: // <-- this is the only edit, use 1 instead of '1'
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
So, to fix your program, change your various case statements to use integer values, not characters.

While loop with iteration

I am trying to create a while loop where the user has a total of three tries to enter a valid number. I'm not understanding how the system recognizes that 3 invalid attempts have been made before displaying the message.
Classes, variables, and scanner objects are made. After the three attempts, I want to say "No more tries". I already have the program written to use the user's input for quantity if its valid. This is just if they input three invalid attempts.
Updated code:
int quantity = 0;
// Get user's desired amount of lemonade cups
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
quantity = keyboard.nextInt(); // Store amount of cups wanted
int attempts = 0;
int maxAttempts = 3;
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
while (attempts < maxAttempts) {
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt(); }
else {
System.out.println("Subtotal: " + defaultFormat.format(subTotal));
System.out.println("Tax: " + defaultFormat.format(totalTax));
System.out.println("Total: " + defaultFormat.format(totalPrice));
}
attempts++;
if (attempts >= 3) {
System.out.print ("No lemonade for you");
break;
}
// Ask for user's payment method
Scanner method = new Scanner(System.in);
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
String payment = method.nextLine();
dxdy is correct about the braces required for making the while() loop function.
Once the while loop has ended (either quantity is between 1 and 20, or attempts > maxAttempts), you just need to have an if statement like the following:
if (attempts > maxAttempts) {
System.out.println("No more tries);
return -1; // or something else to break out of your code
}
and then continue on with the rest of your code working with the quantity variable.
You seem to be missing the opening and closing brackets for the loop. As it is, your code reads
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts)
System.out.println("That is an invalid amount, please try again");
// these below are not part of the loop
quantity = keyboard.nextInt();
attempts++;
Instead you should do
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts){
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt();
attempts++;
}
try this code:
//start with 1 since the user will attempt it at least one time.
int attempts = 1;
int maxAttempts = 3;
int quantity=0;
Scanner keyboard = new Scanner(System.in);
//LESS THAN OR EQUAL TO 3...
while(attempts<=maxAttempts){
System.out.print("Enter amount: ");
quantity = keyboard.nextInt();
//check if valid
if(quantity < 1 || quantity >= 20){
//check if it's 1st and 2nd trial.
if(attempts<maxAttempts){
System.out.println("That is an invalid amount, please try again");
}else{
//third trial and still invalid
System.out.print("No more tries");
}
}else{
//user entered a valid amount so let's break the loops.
System.out.println("The amount is valid. Value of amount: "+ quantity);
break;
}
//increment attempts
attempts++;
}
//never forget to close the scanner
keyboard.close();
}
}
Though I could have turned this into methods if it's allowed
EDIT: As you updated the question, so it was necessary to update the answer too. Here it is what you actually want.
public static void main(String[] args) {
// Get user's desired amount of lemonade cups
String name = "Jimmy Nguyen";
Scanner keyboard = new Scanner(System.in);
int quantity;// Store amount of cups wanted
int lemonadeCost = 4; // Suppose
int attempts = 0;
int maxAttempts = 3;
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
while (attempts < maxAttempts) {
quantity = keyboard.nextInt();
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again\n");
++attempts;
} else {
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
System.out.println("Subtotal: " + subTotal);
System.out.println("Tax: " + totalTax);
System.out.println("Total: " + totalPrice);
// Ask for user's payment method
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
keyboard.nextLine();
String payment = keyboard.nextLine();
break;
}
if (attempts >= 3) {
System.out.print("No lemonade for you");
break;
}
}
}

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.

Two console inputs required to System.exit(0) during else if

So I'm working on a copy of a simple Dice game that was an example from the Maxwell Sanchez YouTube JAVA on Eclipse tutorials. What I started playing around with is simple ways to implement a text based menu of sorts.
What I'm trying to accomplish is a Y or N input method of either restarting the program, or killing it. I'm a total noob, coming here after a tiny bit of Arduino. I'm liking JAVA but there are many things I don't understand.
My problem right now is, everything appears to work so far, except that if you get to the end and type N to quit, It requires 2 inputs of N to actually execute the else if statement. Is that something that is a bug? Or am I just mis-programing what I'm trying to accomplish.
import java.util.*;
public class diceGame
{
static int money;
static Scanner in = new Scanner(System.in);
static Random random = new Random();
static String userName;
static String tryAgain;
public static void main(String[] args)
{
money = 1000;
System.out.println("Welcome to this simple dice game! " +
"Please enter your name.");
String userName = in.nextLine();
System.out.println("Hey " + userName + ".");
rollDice();
}
public static void rollDice()
{
System.out.println("You have " + money + " coins!");
System.out.println("Please select a number (1-6) to bet on!");
int betRoll = in.nextInt();
System.out.println("Please place your bet!");
int betMoney = in.nextInt();
while (betMoney > money)
{
System.out.println("You don't have enough coins... you only " +
"have " + money + "coins.");
System.out.println("Please place a realistic bet!");
betMoney = in.nextInt();
}
int dice;
dice = random.nextInt(6)+1;
if (betRoll == dice)
{
System.out.println("You Win!");
money+=betMoney*6;
System.out.println("You have " + money + " coins.");
}
else
{
System.out.println("Snap! You lost your coins!");
money-=betMoney;
System.out.println("You have " + money + " coins.");
}
if (money <= 0)
{
System.out.println("You've lost all yer coins!");
System.out.println("Play again?" + " Type y or n");
if (in.next().equalsIgnoreCase("y"))
{
System.out.println("Maybe you'll win this time!");
money = 1000;
rollDice();
}
else if (in.next().equalsIgnoreCase("n"))
{
System.out.println("Maybe next time...");
System.exit(0);
}
else
{
System.out.println("Invalid character");
}
}
else
{
rollDice();
}
}
}
Store the input in a variable, and compare it... or you'll have to input twice.
String choice = in.next();
if (choice.equalsIgnoreCase("y"))
{
System.out.println("Maybe you'll win this time!");
money = 1000;
rollDice();
}
else if (choice.equalsIgnoreCase("n")) // <-- not in.next()
Every time you call in.next() you read user input.
if (in.next().equalsIgnoreCase("y"))
else if (in.next().equalsIgnoreCase("n"))
In this code, you are calling in.next() twice, once for each condition, so it will read two inputs.
You need to separate the reading from the comparison.
String input = in.next();
if (input.equalsIgnoreCase("y"))
else if (input.equalsIgnoreCase("n"))

Java - Running totals(using do while and if else statements)

I'm not very adept in getting the running totals using Java as I've started recently. I have to display and hold the running total of the bank balance and for some strange reason, it's resetting back to 100, which is what I declared it as to start with. Is there any way for me to stop the bank balance from being reset every time it loops?
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int choice, totBal = 0, totWith = 0, totDep = 0;
double with, remBal = 0, deposit, bankBal = 100;
char reply = 0;
do
{
System.out.println("");
System.out.println("Bank online\n");
System.out.println("1. Withdraw");
System.out.println("2. Deposit");
System.out.println("3. Balance");
System.out.println("4. Account Details");
System.out.println("5. Exit\n");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
if(choice == 1)
{
System.out.print("How much do you wish to withdraw?\n");
with = sc.nextInt();
remBal = bankBal - with;
System.out.println("Your new balance is: " + remBal);
totWith++;
}
else if(choice == 2)
{
System.out.print("How much do you wish to deposit?\n");
deposit = sc.nextInt();
remBal = remBal + deposit;
System.out.println("Your new balance is: " + remBal);
totDep++;
}
else if(choice == 3)
{
System.out.println("Your balance is: " + remBal);
totBal++;
}
else if(choice == 4)
{
System.out.println("You made " + totWith + " withdrawls from your account.");
System.out.println("You made " + totDep + " deposits to your account.");
System.out.println("You made " + totBal + " balance checks on your account.");
}
else if(choice == 5)
{
}
System.out.println("");
System.out.print("Do you want to enter another option?(y/n): ");
reply = sc.next().charAt(0);
}while(reply == 'Y' || reply == 'y');
System.out.println("Thank you and goodbye!");
}
}
Also, I feel that I have WAY too many variables. How can I cut back on these?
Your problem is with following statement:
double with, remBal = 0, deposit, bankBal = 100;
Here you are initialising remBal as 0, while when one deposits amount/checks balance you do:
remBal = remBal + deposit;//you use remBal for blaance check
So on first attempt it will try to add 0 with say $100 which will be 100 while bankBal is 100 it should be 100. So initialize remBal same as bankBal (or use just one variable for bankBalance i.e. either of one).
You set the bankBal value to 100 at the start of the program.
When doing withdrawals, you always do
remBal = bankBal - with
which will always equate to
remBal = 100 - with
since you never change bankBal to reflect the updated balance after each loop.
One approach to solve this is to remove the
bankBal
variable altogether and simply set your
remBal
variable to your desired starting value.
Finally change the withdrawal computation mentioned above to
remBal = remBal - with
One thing you can do is implement switch-cases to call methods specific to Depost, Withdraw, etc. An example of this roughly would be:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please Enter what you would like to do: ");
String enterPrompt = input.next();
int options = 5;
switch (options) {
case 1: enterPrompt = "Deposit";
doDeposit();
break;
case 2: enterPrompt = "Withdrawel";
doWithdrawel();
break;
case 3: enterPrompt = "Balance";
viewBalance();
break;
case 4: enterPrompt = "Account Details";
viewAccount();
break;
case 5: enterPrompt = "Exit";
System.exit(1);
break;
}
public void doDeposit(){
//local variables here
//Do stuff
}
public void doWithdrawel(){
//local variables here
//Do stuff
}
public void viewBalance(){
//local variables here
//Do stuff
}
public void viewAccount(){
//local variables here
//Do stuff
}
}

Categories