This question already has answers here:
Semicolon at end of 'if' statement
(18 answers)
Closed 6 years ago.
Need help with if else statement in Java. Need the program to say "Sorry, out of stock" when items are at 0. I tried but it wont print out "Sorry, out of stock" Can anyone explain to me how to properly set that up so when the items are at 0 the program will let the user know that the item is out of stock. Thank you.
import java.util.Scanner;
public class VendingMachine {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int Chips = 5;
int Cookies = 4;
int Candies = 3;
double ChipsPrice = 1.25;
double CookiesPrice = 0.85;
double CandiesPrice = 0.95;
Scanner choice = new Scanner(System.in);
Scanner moneyIn = new Scanner(System.in);
while (true) {
double Change = 0;
double Amount = 0;
double Money = 0;
System.out.println("Welcome to the Vending Machine");
System.out.println("Please insert Money");
Amount = moneyIn.nextDouble();
//Make an if statements, such as if moneyIn equals 5 quarters then Amount = 5*0.25
//Ask how many quarters how many nickels how many dimes
System.out.println("What snack would you like?");
System.out.println("Potato Chips: $" + ChipsPrice + " " + Chips + " left");
System.out.println("Cookies: $" + CookiesPrice + " " + Cookies + " left");
System.out.println("Candies: $" + CandiesPrice + " " + Candies + " left");
String which = choice.nextLine();
if (which.equals("Potato Chips")) {
System.out.println("You selected Potato Chips: $" + ChipsPrice + " " + Chips + " left");
if (Amount < ChipsPrice) {
System.out.println("Not enough money inserted");
if (Chips == 0) ;
System.out.println("Sorry, out of stock");
} else {
Chips = Chips - 1;
Change = ChipsPrice - Amount;
System.out.println("Please take your chips ");
System.out.println("Your change is " + Change);
}
} else if (which.equals("Cookies")) {
System.out.println("You selected Cookies: $" + CookiesPrice + " " + Cookies + " left");
Cookies = Cookies - 1;
if (Amount < CookiesPrice) {
System.out.println("Not enough money inserted");
if (Cookies == 0)
System.out.println("Sorry, out of stock");
} else {
Cookies = Cookies - 1;
Change = CookiesPrice - Amount;
System.out.println("Please take your cookies");
System.out.println("Your change is " + Change);
}
} else if (which.equals("Candies")) {
System.out.println("You selected Candies: $" + CandiesPrice + " " + Candies + " left");
if (Amount < CandiesPrice) {
System.out.println("Not enough money inserted");
if (Cookies == 0)
System.out.println("Sorry, out of stock");
} else {
Candies = Candies - 1;
Change = CookiesPrice - Amount;
System.out.println("Please take your candies");
System.out.println("Your change is " + Change);
}
} else {
System.out.println("Please select one of the snacks below");
}
}
}
}
Just to go through this, a few observations:
// It might be simpler to use a "switch" statement here
if (which.equals("Potato Chips")) {
System.out.println("You selected Potato Chips: $"+ChipsPrice+" "+Chips+" left");
if (Amount < ChipsPrice){
System.out.println("Not enough money inserted");
// Remove the semicolon - as written this won't do anything
// Also, this condition shouldn't be here since you're not vending anyway
// Incidentally, many people argue that you should always use curly
// brackets, even around one-line "if" statements like this, precisely
// to prevent errors like this
if (Chips == 0);
System.out.println("Sorry, out of stock");
}
else {
// This can be written as Chips--;
Chips = Chips - 1;
// Should actually be Amount - ChipsPrice;
// If they paid 75 cents for a 25-cent item, the change is 75 - 25 = 50 cents,
// NOT 25 - 75 = -50 cents
Change = ChipsPrice - Amount;
System.out.println("Please take your chips " );
System.out.println("Your change is "+ Change );
}
}
else if (which.equals("Cookies")) {
System.out.println("You selected Cookies: $"+CookiesPrice+" "+Cookies+" left");
// Cookies--
Cookies = Cookies - 1;
if (Amount < CookiesPrice){
System.out.println("Not enough money inserted");
// Should be checked in the "else" statement
if (Cookies == 0)
System.out.println("Sorry, out of stock");
}
else {
// Cookies--
Cookies = Cookies - 1;
// Amount - CookiesPrice
Change = CookiesPrice - Amount;
System.out.println("Please take your cookies");
System.out.println("Your change is "+ Change );
}
}
else if (which.equals("Candies")) {
System.out.println("You selected Candies: $"+CandiesPrice+" "+Candies+" left");
if (Amount < CandiesPrice){
System.out.println("Not enough money inserted");
// Again, you shouldn't check this here given that you won't vend either way
// Also, should be if (Candies == 0), NOT if (Cookies == 0)
if (Cookies == 0)
System.out.println("Sorry, out of stock");
}
else {
// Candies--;
Candies = Candies - 1;
// Should actually be Amount - CandyPrice. You use CookiesPrice instead.
Change = CookiesPrice - Amount;
System.out.println("Please take your candies");
System.out.println("Your change is "+ Change );
}
}
else {
System.out.println("Please select one of the snacks below");
}
One more thing: you're basically doing the same exact thing 3 consecutive times; in situations like that, it's usually better to try to refactor the behavior in question as a method (rather than typing it 3 separate times).
Related
I am trying to figure out why I cannot get the loop to break if either "n" is input for playAgain or when the total is below $10. If you see how I can break the loop to run the gameOver function without having an exception thrown that would be a great help. I have noted in the code below that I am having trouble with. I am unsure why this exception is being thrown. If you are able to find out how to break the loop when total is less than 10 or when playAgain is false please let me know!
import java.util.Random;
import java.util.Scanner;
public class GameOfCrapsTester {
static Scanner in = new Scanner(System.in);
static Random rand = new Random();
public static void main(String[] args) {
System.out.println("Welcome to the game of Craps");
System.out.println(" ");
System.out.println("The house has given you a starting balance of $500");
System.out.println("On each round, you will make a whole number wager.");
System.out.println("The minimum wager is $10, and the maximum wager is your remaining balance.");
System.out.println(" ");
System.out.println("You may keep playing until you decide to cash in, or");
System.out.println(" you can't cover the minimum wager.");
System.out.println("Good Luck!");
boolean win;
double wins = 0, numOfGames = 0;
int total = 500;
// Come out roll and set point value
int pointValue = 0;
boolean playAgain = true;
while (playAgain && total > 0)
{
System.out.println(" ");
System.out.println("Your balance is $" + total);
System.out.println(" ");
System.out.println("Place your bet: $");
// Get and check wager placed
int bet = in.nextInt();
while (bet > total || bet < 10)
{
if (bet < 10)
{
System.out.println("Bet must be larger than $10.");
}
System.out.println("I'm sorry, that's not a valid wager; please re-enter: ");
bet = in.nextInt();
}
int num = rollDice();
if ((num >= 4 && num <= 10 && num != 7) || num == 0)
{
pointValue = num;
System.out.println(" ");
System.out.println("Your point value is " + pointValue);
System.out.println(" ");
win = rollWithPoint(pointValue);
if (win)
{
total = wonGame(bet, total);
wins++;
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
else if (!win)
{
total = lostGame(bet, total);
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
}
else if (num == 7 || num == 11)
{
total = wonGame(bet, total);
wins++;
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
else
{
total = lostGame(bet, total);
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
if (total <= 9) // THIS IS WHERE I AM HAVING TROUBLE
{
break;
}
System.out.println("Keep playing (y/Y or n/N)? ");
in.nextLine();
String again = in.nextLine();
if (again.equalsIgnoreCase("y"))
{
playAgain = true;
}
else if (again.equalsIgnoreCase("n")) // THIS IS WHERE I AM HAVING TROUBLE
{
break;
}
else
{
System.out.println("Invalid character input, try again:");
again = in.nextLine();
}
}// end of loop
gameOver(wins, numOfGames);
} // END of main
public static int rollDice() {
int dice1, dice2, total;
dice1 = rand.nextInt(6) + 1;
dice2 = rand.nextInt(6) + 1;
total = dice1 + dice2;
System.out.print("Your roll: ");
System.out.print("Dice1: " + dice1);
System.out.print(", Dice2: " + dice2);
System.out.println("; Roll Value: " + total);
return total;
} // END of rollDice
public static boolean rollWithPoint(int point) {
int total = rollDice();
boolean winner = false;
while(total != 7 && winner == false)
{
total = rollDice();
if (total == point)
{
winner = true;
}
else
{
winner = false;
}
}
return winner;
} // END of rollWithPoint
public static int lostGame(int bet, int total) {
System.out.println("Oh, I'm sorry, you lost.");
System.out.println(" ");
total = total - bet;
System.out.println("Your current balance: $" + total);
System.out.println(" ");
return total;
} // END of lostGame
public static int wonGame(int bet, int total) {
System.out.println("A winner!");
System.out.println(" ");
total = total + bet;
System.out.println("Your current balance: $" + total);
System.out.println(" ");
return total;
} // END of wonGame
public static void gameOver(double win, double tot) {
double winPercent = (win / tot) * 100;
System.out.println(" ");
System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);
System.out.println(" ");
System.out.println("Seems you lost your shirt; better luck next time.");
System.out.println("Have a nice day! Hope to see you soon!");
} // END of gameOver
} // END of GameOfCraps
There is no error when you change this (without using String.format()):
System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);
To this:
System.out.println("Based on your play, the probability of winning is " + winPercent + "%.");
Example with a little bet (console):
Your balance is $11
Place your bet: $
10
Your roll: Dice1: 1, Dice2: 2; Roll Value: 3
Oh, I'm sorry, you lost.
Your current balance: $1
Wins: 0.0 Number of games: 2.0
Based on your play, the probability of winning is 0.0%.
Seems you lost your shirt; better luck next time.
Have a nice day! Hope to see you soon!
I cannot get the loop to break if either "n" is input for playAgain or
when the total is below $10.
It works fine too. If I put a bet below 10 it asks me to put another bit. What
In summary my program is not accounting for each additional topping that is included on the pizza and then adding 1.25 to the base cost as expected and then appropriately computing the tax and finally producing the overall total. My brain is in a haze trying to figure it out. Any pointers?
I'm stumped on what could even be a potential solution so I'm not quite sure what to try.
import java.util.Scanner;
public class PizzaOrder {
public static void main(String[] args) {
//Declared variables
String firstName; // First name of user
char crustType; // Type of crust
String crustName; // Name of crust
int inches; // Pizza size
final double Tax_Rate = 0.08; // Tax Rate
double baseCost = 0.0; // Cost of pizza without tax and additional toppings.
double total; // base cost plus the toppings
double overallTotal; // Total cost including toppings and tax
double tax; // Tax amount
String toppings = "Cheese"; // Toppings list
String choice;
int numberOfToppings = 0; // Toppings counter
// Create Scanner object
Scanner keyboard = new Scanner(System.in);
//Prompt and get the users first name
System.out.println("Welcome to Mike and Diane's Pizza.");
System.out.print("Enter your first name: ");
firstName = keyboard.nextLine();
//Prompt and get pizza size
System.out.println("Pizza Size(inches) Cost");
System.out.println(" 10 $10.99 ");
System.out.println(" 12 $12.99 ");
System.out.println(" 14 $14.99 ");
System.out.println(" 16 $16.99 ");
System.out.print("Enter the size of the pizza you would like: ");
inches = keyboard.nextInt();
keyboard.nextLine(); //Consuming end of line character
if(inches == 10) {
baseCost = 10.99;
}
else if(inches == 12) {
baseCost = 12.99;
}
else if(inches == 14) {
baseCost = 14.99;
}
else if(inches == 16) {
baseCost = 16.99;
}
else if(inches != 10 && inches != 12 && inches != 14 && inches != 16) {
System.out.print("You have entered an invalid choice. The pizza size" +
" will be set to 12 inches. ");
}
// Prompt and get crust choice
System.out.print("Enter the type of crust you would like. " +
" (H)and-Tossed, (T)hin-Crust, or (D)eep-Dish: ");
crustName = keyboard.nextLine();
crustType = crustName.charAt(0);
// Output if the user selects Hand-Tossed
if(crustType == 'H' || crustType == 'h') {
crustName = "Hand-Tossed";
System.out.println("You selected Hand-Tossed pizza. ");
}
// Output if the user selects Thin-Crust.
else if(crustType == 'T' || crustType == 't') {
crustName = "Thin-Crust";
System.out.println("You selected Thin Crust pizza. ");
}
// Output if the user selects Deep-dish.
else if(crustType == 'D' || crustType == 'd') {
crustName = "Deep-dish";
System.out.println("You selected Deep-Dish pizza. ");
}
// Otherwise print out the default pizza type.
else {
System.out.print("You have entered an invalid choice. The crust type" +
"will be set to Hand-Tossed. ");
}
// Display message about toppings and additional cost
System.out.println("All pizzas come with cheese.");
System.out.println("Additional toppings are $1.25 each. Please choose" +
" from Pepperoni, Onion, Sausage, and Mushroom. ");
// Prompt and get topping choices one at a time. If topping is desired, add
// name to topping list and increment number of toppings.
System.out.print("Would you like pepperoni added? (Y/N): ");
choice = keyboard.nextLine();
if (choice.equals("Y") || choice.equals('y')) {
numberOfToppings = numberOfToppings + 1;
toppings = toppings + " and pepperoni.";
}
else {
numberOfToppings = 0;
}
//Prompt for sausage and store in numberOfToppings
System.out.print("Would you like sausage added? (Y/N): ");
choice = keyboard.nextLine();
if (choice.equals("Y") || choice.equals('y')) {
numberOfToppings = numberOfToppings + 1;
toppings = toppings + " and sausage.";
}
else {
numberOfToppings = 0;
}
//prompt for onion and store in numberOfToppings
System.out.print("Would you like onion added? (Y/N): ");
choice = keyboard.nextLine();
if (choice.equals("Y") || choice.equals('y')) {
numberOfToppings = numberOfToppings + 1;
toppings = toppings + " and onion.";
}
else {
numberOfToppings = 0;
}
//prompt for mushroom and store in numberOfToppings
System.out.print("Would you like mushroom added? (Y/N): ");
choice = keyboard.nextLine();
if (choice.equals("Y") || choice.equals('y')) {
numberOfToppings = numberOfToppings + 1;
toppings = toppings + " and mushroom.";
}
else {
numberOfToppings = 0;
}
//Calculation of cost
total = ((baseCost) + (numberOfToppings * 1.25));
tax = total * Tax_Rate;
overallTotal = total * (1 + Tax_Rate);
// Payment Confirmation
System.out.println(firstName + ", here is your order:");
System.out.println(inches + " inch pizza");
System.out.println(crustName + ", " + toppings);
System.out.println("The cost of your order is: $" + (total));
System.out.println("The tax is: $" + (tax));
System.out.println("The overall total due is: $" + (overallTotal));
}
}
The expected output would take the base cost, add 1.25 times whatever number of toppings, compute the tax and then add the tax to the cost that includes the toppings. Can anyone help please?
You need to get rid of else block. Instead of :
if (choice.equals("Y") || choice.equals('y')) {
numberOfToppings = numberOfToppings + 1;
toppings = toppings + " and sausage.";
}
else {
numberOfToppings = 0;
}
It should be like this everwhere:
if (choice.equals("Y") || choice.equals('y')) {
numberOfToppings = numberOfToppings + 1;
toppings = toppings + " and sausage.";
}
If at any point the user enters other than 'Y' or 'y', number of toppings will be resetted to 0.
Also, I Don't understand what this line is doing
overallTotal = total * (1 + Tax_Rate);
According to what you asked, the logic should be:
overallTotal = total + tax;
You can also use the Switch case statement in place of the IfElse ladder.
Hope this helps !!!
This is my first post here, so forgive me for any formatting errors.
So as you can see my program requests the gender, # of accidents and year of car to display a fictitious insurance quote.
Based on all that information I need to add the subtotal of the insurance cost to the end.
I have my code working up until the Total Cost comment (posted it all for reference). I am stuck there because the genders have different base amounts. I'm trying to figure out a way to only do one if statement if it matches the gender that was input by the user.
Any ideas?
import java.util.*;
public class Insurance {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
int currentYear = 2017; //used for calculating the age of the users car
int maleGender = 1000;
int femaleGender = 500;
//Letting user know they are inputting data for car insurance purposes
System.out.println("Car insurance questionnaire. Please input correct information when prompted.");
// gender information from user
System.out.println("What is your gender? m/f");
String gender = scanner.next();
// accident quantity information from user
System.out.println("How many accidents have you had?");
int acc = scanner.nextInt();
// car year information from user
System.out.println("What year was your car manufactured?");
int carAge = scanner.nextInt();
//if statements which refer to the users data input
if (gender.equals("m")) {
System.out.println("You are a male.\nThe base cost is $1000.");
} else {
System.out.println("You are a female.\nThe base cost is $500.");
}
if (acc == 0) {
System.out.println("You have no accidents. Insurance increase is $0.");
} else if (acc >= 1) {
System.out.println("You have " + acc + " accidents. Insurance increase is $" + acc * 100 + ".");
}
if (carAge >= 2007) {
System.out.println("Your car is " + (currentYear - carAge) + " years old.\nYour car is still in warranty, no savings added.");
} else
System.out.println("Your car is out of warranty, final cost is halved.");
//Total cost
/*
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + femaleGender) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + femaleGender) + ".");
*/
}
}
I am not totally sure how you want to calculate your result but if do NOT want to use femaleGender all the time but in dependency of the gender different values then maybe something like this could help:
int baseAmount = gender.equals("m") ? maleGender : femaleGender;
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + baseAmount ) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + baseAmount ) + ".");
}
int genderCost;
...
if (gender.equals("m")) {
System.out.println("You are a male.\nThe base cost is $1000.");
genderCost = maleGender;
} else {
System.out.println("You are a female.\nThe base cost is $500.");
genderCost = femaleGender;
}
...
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + genderCost) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + genderCost) + ".");
}
Put the amount for gender in a variable genderCost when the gender input variable is evaluated and use genderCost when you calculate the total.
I'm trying to print out different variables I've already declared in different switch cases, they're all in one switch block in a for loop but the compiler isn't allowing me use the variables. Giving me a "cannot find symbol" error.
Here's the code:
public static void main(String[] args) {
double hammer = 3.25, nails = 5.25, paint = 4.75, paintBrush = 2.25, balance = 50.00;
Scanner input = new Scanner(System.in);
System.out.println("Local Hardware Point of Sales");
System.out.println("\t::MENU::");
System.out.println("1. Purchase Items\n2. Display current purchases\n3. Display account balance\n4. Complete transactions and Exit");
System.out.print("Enter choice: ");
int choice = input.nextInt();
switch(choice){
case 1:
for(int i = 0; i <= 2; i++){
System.out.println("\n\tPurchase Items");
System.out.println("What items would you like to purchase?");
System.out.println("\tItems \t\tPrices");
System.out.println("\tHammer\t\t-$3.25\n\tNails\t\t-$3.25\n\tPaint\t\t-$3.25\n\tPaint Brush\t-$3.25");
String item = input.next();
switch (item) {
case "Hammer":
case "hammer":
System.out.println("How many Hammers would you like to purchase?");
int hItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double hPrice = hItem*hammer;
System.out.println("Cost for " + hItem + " Hammers: $" + hPrice);
double hBalance = balance - hPrice;
System.out.println("Final Balance: $" + hBalance);
if(hBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ hItem+ " Hammers (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+hItem+"Hammers for "+ hPrice);
}
}
break;
case "Nails":
case "nails":
System.out.println("How many Nails would you like to purchase?");
int nItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double nPrice = nItem*nails;
System.out.println("Cost for " + nItem + " Nails: $" + nPrice);
double nBalance = balance - nPrice;
System.out.println("Final Balance: $" + nBalance);
if(nBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ nItem+ " Nails (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+nItem+" Nails for "+ nPrice);
}
}
break;
case "Paint":
case "paint":
System.out.println("How many Paints would you like to purchase?");
int pItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double pPrice = pItem*nails;
System.out.println("Cost for " + pItem + " Paints: $" + pPrice);
double pBalance = balance - pPrice;
System.out.println("Final Balance: $" + pBalance);
if(pBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ pItem+ " Paints (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+pItem+" Paints for "+ pPrice);
}
}
break;
case "Paint Brush":
case "paint brush":
System.out.println("How many Paint Brushes would you like to purchase?");
int pbItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double pbPrice = pbItem*nails;
System.out.println("Cost for " + pbItem + " Paint Brushes: $" + pbPrice);
double pbBalance = balance - pbPrice;
System.out.println("Final Balance: $" + pbBalance);
if(pbBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ pbItem+ " Paint Brushes (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+pbItem+" Paint Brushes for "+ pbPrice);
}
}
break;
default:
break;
}
System.out.println("\nMake another purchase? (Y/N)");
String ans = input.next();
if(ans.equals("n"))
System.out.println("\tCurrent Receipt");
System.out.println("Items \t\tQuantity \t\tPrice Per \t\tTotal Price");
System.out.println("Hammer \t\t"+**hItem**+" \t\t\t"+hammer+" \t\t\t"+**hPrice**);
System.out.println("Nails \t\t"+**nItem**+" \t\t\t"+nails+" \t\t\t"+**nPrice**);
System.out.println("Paint \t\t"+**pItem**+" \t\t\t"+paint+" \t\t\t"+**pPrice**);
System.out.println("Paint Brush \t\t"+**pbItem**+" \t\t\t"+paintBrush+" \t\t\t"+**pbPrice**);
}
}
}
}
I bolded the variables that are giving the error. P.s I am not allowed to use methods for this project, strictly conditional statements and loops.
Also if anyone doesn't mind, I'm trying to get string input for "Paint Brush" but using input.next() has issues with the space, and when I used input.nexLine() it completely ignored the input and ended the program, so had to revert back to next().
Please if anyone can help, much appreciated. Thanks alot
Declare the variables that give you an error outside of the switch-case. Currently their scope is limited to only the inside of the case part, meaning that for the rest of the code (outside of the case) they don't exist.
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;
}
}
}