Sentinel value does not exit while loop - java

// In the following program, initally when the user is greeted with the instructions he can simply enter the sentinel to exit the while loop, however, when you get the result of tickets you wish to buy, pressing 999 does not exit the program
import java.io.*;
public class ManyTickets
{
public static void main (String [] args) throws IOException
{
String userInput;
String userInput2;
int intInput = 0;
int intInput2 = 0;
double total = 0.00;
BufferedReader ageInput = new BufferedReader (new InputStreamReader (System.in));
try{
System.out.println("Please enter your age, or press '999' to exit.");
userInput = ageInput.readLine();
intInput = Integer.parseInt (userInput);
while (intInput != 999)
{
if (intInput < 0 || intInput > 110)
System.out.println("Invalid entry, or your age seems a bit too high to enter buy these tickets");
else if (intInput <= 12)
{
total = total + 6;
System.out.println("The ticket cost for 1 ticket is " + total);
}
else if (intInput <= 64)
{
total = total + 11;
System.out.println("The ticket cost for 1 ticket is " + total);
}
else
{
total = total + 8;
System.out.println("The ticket cost for 1 ticket is $" + total);
}
System.out.println("So far, your tickets cost is: $" + total );
System.out.print("Would you like to buy more tickets? You can buy up to 1 more ticket per customer! If no press 999 to exit");
userInput = ageInput.readLine();
intInput2 = Integer.parseInt (userInput);
}
}catch (NumberFormatException e){
System.out.println("Please restart the program, and enter an integer instead!");
}
}
{
double total = 0.0;
System.out.println("Thank you, The total cost for the ticket is: $" + total);
System.out.println("Have a nice day!");
}
}

You're using two different variables, intInput and intInput2. I don't see why you need the second one (right before the catch block). Just reuse intInput, which is the one being checked against the sentinel value in your while loop.

You are not doing anything after the user enters 999. Break the loop when its 999 as below,
intInput2 = Integer.parseInt(userInput);
if (intInput2 == 999) {
break;
}

Related

Throws Exception when trying to break loop because a condition has been met

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

(JAVA) do while loop for my vending machine

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

Skipping a number in a for loop sequence?

so I have another homework question. First, I'll list the instructions and then I'll list my code and hopefully someone can help me/guide me in the right direction.
DIRECTIONS:
Write a program that calculates the occupancy rate for a hotel. The program should start by asking the user how many floors the hotel has. A for loop should then iterate once for each floor. In each iteration of the for loop, the program should ask the user for the number of rooms of the floor and how many of them are occupied. After all of the iterations are complete the program should display how many rooms the hotel has, how many of them are occupied, and the percentage of rooms that are occupied.
It is traditional that many hotels do not have a 13th floor. The for loop in >this program should skip the entire thirteenth loop iteration.
Input validation (remember to use a loop never ever an "if"): Do not accept a value of less than one for the number of floors. Do not accept a value of less than 10 for the number of rooms on a floor.
MY CODE:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Homework7Hotel
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner (System.in);
DecimalFormat formatter = new DecimalFormat("%#,##0.00");
int numFloors = 0;
int numRooms = 0;
int totalRooms = 0;
int numOccupied = 0;
int totalOccupied = 0;
int percentOccupied = 0;
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
while (numFloors <1)
{
System.out.println("You have entered an invalid number of floors. ");
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
}
for (int counter = 1; counter <=numFloors; counter++)
{
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms=keyboard.nextInt();
totalRooms += numRooms;
while (numRooms <10)
{
System.out.println("You have entered an invalid number of rooms. ");
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms = keyboard.nextInt();
}
System.out.println("Please enter the number of occupied rooms on floor #: " + counter);
numOccupied = keyboard.nextInt();
totalOccupied += numOccupied;
// *not sure of how to do this* percentOccupied = totalOccupied/totalRooms;
}
System.out.println("The hotel has a total of " + totalRooms + " rooms.");
System.out.println(totalOccupied + " of the rooms are occupied.");
System.out.println (percentOccupied + "% of the rooms are occupied.");
}
}
So, the issue I am having is:
1) As per the instructions, how would I skip the 13th floor entirely in the loop?
Any help would be greatly appreciated! Thank you!
You could use a continue keyword in a forloop like.
for(int i = 0;i <20;i++){
if(i == 13){
continue;
}
//Do rest of your steps
}
If you donot want to use continue use
for(int i = 0;i <20;i++){
if(i != 13){
//Do rest of your steps
}
//This should also work it will not do anything when loop is at its 13th iteration.
}
Using continue though is better.
public static void main (String[] args)
{
Scanner keyboard = new Scanner (System.in);
DecimalFormat formatter = new DecimalFormat("%#,##0.00");
int numFloors = 0;
int numRooms = 0;
int totalRooms = 0;
int numOccupied = 0;
int totalOccupied = 0;
int percentOccupied = 0;
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
while (numFloors <1)
{
System.out.println("You have entered an invalid number of floors. ");
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
}
for (int counter = 1; counter <=numFloors; counter++)
{
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms=keyboard.nextInt();
//REMOVE totalRooms += numRooms; from here
while (numRooms <10)
{
System.out.println("You have entered an invalid number of rooms. ");
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms = keyboard.nextInt();
}
totalRooms += numRooms; //ADD it here
System.out.println("Please enter the number of occupied rooms on floor #: " + counter);
numOccupied = keyboard.nextInt();
totalOccupied += numOccupied;
// *not sure of how to do this* percentOccupied = totalOccupied/totalRooms;
}
System.out.println("The hotel has a total of " + totalRooms + " rooms.");
System.out.println(totalOccupied + " of the rooms are occupied.");
System.out.println (percentOccupied + "% of the rooms are occupied.");
}
Without continue, you can try if() else block to do the work.
for(int i = 0; i < 20; i++)
{
if(i == 13)
{
// Do the stuff for 13th floor if any
}
else
{
// Do the stuff for floors other than 13
}
}

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

Java - adding value in a while loop

this one just is hurting my brain. http://programmingbydoing.com/a/adding-values-in-a-loop.html
Write a program that gets several integers from the user. Sum up all the integers they give you. Stop looping when they enter a 0. Display the total at the end.
what ive got so far:
Scanner keyboard = new Scanner(System.in);
System.out.println("i will add");
System.out.print("number: ");
int guess = keyboard.nextInt();
System.out.print("number: ");
int guess2 = keyboard.nextInt();
while(guess != 0 && guess2 != 0)
{
int sum = guess + guess2;
System.out.println("the total so far is " + sum);
System.out.print("number: ");
guess = keyboard.nextInt();
System.out.print("number: ");
guess2 = keyboard.nextInt();
System.out.println("the total so far is " + sum);
}
//System.out.println("the total so far is " + (guess + guess2));
}
Declare the int sum variable outside of the while loop and only have one guess = keyboard.nextInt() inside the loop. Add the user's guess to the sum in the loop as well.
Then after the loop output the user's sum.
I.e.:
int sum;
while(guess != 0)
{
guess = keyboard.nextInt();
sum += guess;
}
System.out.println("Total: " + sum");
Edit: also remove the guess2 variable, as you will no longer need it.
The code will be as below :
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
int input = 0;
int total = 0;
System.out.println("Start entering the number");
while((input=keyboard.nextInt()) != 0)
{
total = input + total;
}
System.out.println("The program exist because 0 is entered and sum is "+total);
}
Programming by Doing :)
int x = 0;
int sum = 0;
System.out.println("I will add up the numbers you give me.");
System.out.print("Number: ");
x = keyboard.nextInt();
while (x != 0) {
sum = x + sum;
System.out.println("The total so far is " + sum + ".");
System.out.print("Number: ");
x = keyboard.nextInt();
}
System.out.println("\nThe total is " + sum + ".");
import java.util.Scanner;
public class AddingInLoop {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number, total = 0;
System.out.print("Enter a number\n> ");
number = keyboard.nextInt();
total += number;
while (number != 0) {
System.out.print("Enter another number\n> ");
number = keyboard.nextInt();
total += number;
}
System.out.println("The total is " + total + ".");
}
}
You first prompt the user to enter a number. Then you store that number into total (total += number OR total = total + number). Then, if the number entered wasn't 0, the while loop executes. Every time the user enters a nonzero number, that number is stored in total ( the value in total is getting bigger) and the while loops asks for another number. If and when a user enters 0, the while loop breaks and the program displays the value inside total. :D I myself am a beginner and had a bit of an issue with the logic before figuring it out. Happy coding!

Categories