Tip Calculator statement confusion - java

Here is the code. Basically after I enter the second customers bill amount it will prematurely read me a tip and asks if there is another customer. I want it to ask me if there is another customer but I don't want it to ask about the tip till I enter "n". Any thoughts?
import java.util.Scanner;
public class H3_TipCalc {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Please enter your bill amount.");
double bill = input.nextDouble();
String multiplecust = ("Y");
//int mc=1;
while (multiplecust.equalsIgnoreCase("y"))
{
Scanner usrin = new Scanner (System.in);
System.out.println("Is there another customer? y or n?");
multiplecust = usrin.nextLine();
//mc++;
if (multiplecust.equals("y")){
System.out.println("Please enter their bill amount.");
}
else if (multiplecust.equals("n")){
System.out.println("What tip prcentage would you like to use? Enter as a decimal.");
}
double tip = usrin.nextDouble();
System.out.println("Your tip owed will be " + bill*tip + ".");
}
}
}

Because of the else if, you can either enter the last customer's bill amount or the tip percentage, but not both. Instead, try this logic:
while( there are more individual customer amounts to enter ) {
enter next customer amount
}
get tip percentage
show final bill
Notice that the tip percentage is entered after the while loop, because it's just a one-time entry.

You got your logic twisted.
Better move the complete logic inside the loop and check for exit at the end of it (not the start):
do
read bill amount
read tip amount
read next customer
while (wants to continue)

Related

Java - Do you want to continue?(Y/N)

I want to write a simple loop for the program to go back and restart it again.
Just a simple 1 question program. Then the system ask if the user want to do it again. If the user inputs Y ... the program will loop it back to the beginning and run the entire program again. If the user inputs N, it exits.
import java.util.Scanner; // show them as code
public class HowToDoLoop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
while(true){
System.out.println("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
String c = input.nextLine();
if(c.equalsIgnoreCase("n")){
break;
}//else continue to loop on any string ;-)
}
String c = "";
do{
System.out.println("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
c = input.nextLine();
}while(c.equalsIgnoreCase("Y"));

Exception Thread in Do-While Loop

I'm working on a project that calculates the value of a bank account based on starting balance(b), interest rate(IR), and quarters to display. My entire code works perfectly, but the very last portion is to make sure the variables like interest rate are within the confines of the boundaries my professor gave me. I do need to display an error message if the user enters a value outside the boundaries and ask for the value again.
For example, the number of quarters to display needs to be greater than zero, and less or equal to 10.
As you can see, pretty much all of my program is in a do-while loop. I know I can have nested loops, but what would I be able to put in my do-while loop that would work in this situation? An if-else statement? Try and catch block? Another while loop?
If I used a try-catch, then could anyone give me an example of how I could do that? Thank you very much for your time, and all help is appreciated! The below is my code for reference.
import java.util.Scanner;
public class InterestCalculator
{
public static void main(String[] args)
{
Scanner scannerObject = new Scanner(System.in);
Scanner input = new Scanner(System.in);
int quartersDisplayed;
double b, IR;
do
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
quartersDisplayed = keyboard.nextInt();
System.out.println("Next enter the starting balance. ");
System.out.println("This input must be greater than zero: ");
b = keyboard.nextDouble();
System.out.println("Finally, enter the interest rate ");
System.out.println("which must be greater than zero and less than or equal to twenty percent: ");
IR = keyboard.nextDouble();
System.out.println("You have entered the following amount of quarters: " + quartersDisplayed);
System.out.println("You also entered the starting balance of: " + b);
System.out.println("Finally, you entered the following of interest rate: " + IR);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = b + (b * IR/100 * .25);
System.out.println("Your ending balance for your quarters is " + quarterlyEndingBalance);
System.out.println("Do you want to continue?");
String yes=keyboard.next("yes");
if (yes.equals(yes))
continue;
else
break;
}
while(true);
}
}
So here's some code to answer your questions and help get you started. However, there are problems with your logic that do not pertain to your question which I will address afterward.
Note: I have added comments to your code. Most of them start with "EDIT:" so that you can tell what I changed. I didn't use this prefix in all cases because some of it is new code and it's obviously my comment
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
// EDIT: you already have a scanner defined below with a more meaningful name so I removed this one
// Scanner scannerObject = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//EDIT: defining userResponse outside the loop so we can use it everywhere inside
String userResponse = null;
do {
//EDIT: moved the variables inside the loop so that they are reset each time we start over.
//EDIT: initialize your variable to a value that is invalid so that you can tell if it has been set or not.
int quartersDisplayed = -1;
//EDIT: gave your variables more meaningful names that conform to java standards
double startingBalance = -1, interestRate = -1;
//EDIT: you don't need a second Scanner, just use the one you already have.
// Scanner keyboard = new Scanner(System.in);
do{
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
do{
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try{
startingBalance = Double.parseDouble(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
if(startingBalance <= 0){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
do{
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try{
interestRate = Double.parseDouble(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
//Note: I assume twenty percent is represented as 20.0 here
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
System.out.println("You have entered the following amount of quarters: "
+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "
+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "
+ quarterlyEndingBalance);
System.out.println("Do you want to continue?");
//EDIT: modified your variable name to be more meaningful since the user's response doesn't have to "yes" necessarily
userResponse = input.next();
// EDIT: modified the logic here to compare with "yes" or "y" case insensitively.
// if (userResponse.equals(userResponse))
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
} while (true);
Now to address other issues - your interest calculation doesn't seem correct to me. Your formula does not make use of the quartersDisplayed variable at all. I assume you're compounding the interest quarterly so you will definitely need to make use of this when calculating your results.
This may be beyond the scope of your project, but you should not use double or float data types to represent money. There is a stackoverflow question about this topic that has good information.
Possible improvements - since you're asking the user for two values of type double you could create a method to ask for a double value and call it twice instead of repeating the code. This is a better approach because it helps reduce the chance of mistakes and makes testing and maintenance easier.
You can do something like this in your do/while loop:
do
{
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
quartersDisplayed = keyboard.nextInt();
}
while (quartersDisplayed < 1 || quartersDisplayed > 10);
System.out.println("Next enter the starting balance. ");
do
{
System.out.println("This input must be greater than zero: ");
b = keyboard.nextDouble();
}
while (b < 1);
// rest of code ...
}
With the Scanner#hasNextInt (and the equivalent for double), you can avoid having exceptions thrown, and thus don't need try-catch clauses. I think in general if you can avoid try-catch, it's good, because they are clumsy - but I might be wrong.
However, my approach is like this. Inside your outer do-while, have three other do-while-loops to get the three values. The reason is that you want to keep looping until you get a correct value. The explanation of why keyboard.nextLine() is important is covered here.
I didn't include all of your code, only the part in question. Here's my take on it:
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int quartersDisplayed = -1;
double b = -1.0;
double IR = -1.0;
do {
do {
System.out.println("Enter the number of quarters.");
if(keyboard.hasNextInt()) {
quartersDisplayed = keyboard.nextInt();
keyboard.nextLine(); //important
} else {
System.out.println("You need to enter an integer.");
continue;
}
} while(quartersDisplayed < 1 || quartersDisplayed > 10);
do {
System.out.println("Enter the starting balance.");
if(keyboard.hasNextDouble()) {
b = keyboard.nextDouble();
keyboard.nextLine();
} else {
System.out.println("You must enter a number.");
continue;
}
} while(b <= 0);
do {
System.out.println("Enter the interest rate.");
if(keyboard.hasNextDouble()) {
IR = keyboard.nextDouble();
keyboard.nextLine();
} else {
System.out.println("You must enter a number.");
continue;
}
} while(IR <= 0 || IR > 20.0);
//... rest of code
} while(true);
}
}

Why is my Java for/if/else statement outputting duplicates

I am practicing using loops in Java and I have created this if/else loop to continually ask if there is another customer, if the user input is
"Yes" then it asks for that customers bill.
"No" then I am going to total the bill (I haven't written code for that yet so ignore that part).
The problem I am having is after I enter the initial bill amount the code asks if there is another customer like it should, but then prematurely asks for their bill amount and then asks if there is another customer a second time?
My main question is, did I structure this wrong? How am I able to get the loop to not output something twice and/or prematurely?
Scanner input = new Scanner(System.in);
double total;
System.out.println("Please enter your bill amount.");
double bill0 = input.nextDouble();
for(int c = 0; c > -1; c++) {
System.out.println("Is there another customer?");
String customer = input.nextLine();
if (customer.equalsIgnoreCase("Yes")) {
System.out.println("Please enter their bill.");
double bill = input.nextDouble();
} else {
System.out.println("Okay, let's total your bill amount.");
}
}
for(int c = 0; c > -1; c++)
This loop will (basically) run forever as c will always be greater than -1.
(Actually this loop will run until overflow occurs because the value of c will be too big to fit in the available storage space allocated for this integer. You can refer here for more information: http://en.wikipedia.org/wiki/Integer_overflow)
A cleaner way to structure this would be to do something like:
String answer = "Yes";
while (answer.equals("Yes"))
{
System.out.println("Please enter your bill amount.");
double bill0 = input.nextDouble();
System.out.println("Is there another customer? (Yes or No)");
answer = input.nextLine();
}
Of course, you need to add error handling if the user enters inputs that you are not expecting. Also, this is more pseudocode than a true implementation.
After this while loop is when you would want to total the amount. Also, in the while loop you might want to have a variable keeping the total amount. Something like:
total += bill0;
after the line:
double bill0 = input.nextDouble();
might do the trick.
Matt Jones is correct - your loop (basically) runs forever - (overflow means it doesn't truly run forever, but it's close enough).
It seems you're trying to break the loop once the user enters "No". That means you don't know how many iterations you're going to need, so a while loop is more suited to this task than a for loop. So let's use a while loop to do that.
Scanner input = new Scanner(System.in);
double total;
System.out.println("Please enter your bill amount.");
double bill0 = input.nextDouble();
//loop until the user enters the phrase "No".
while(true) {
System.out.println("Is there another customer?");
String customer = input.nextLine();
if (customer.equalsIgnoreCase("Yes")) {
System.out.println("Please enter their bill.");
double bill = input.nextDouble();
} else if(customer.equalsIgnoreCase("No") {
System.out.println("Okay, let's total your bill amount.");
break; //End the loop
} else{
System.out.println("Sorry, unrecognized input. Please enter yes or no.");
}
}
//Do post-loop totaling and stuff.
I would use a while loop
while (scannerInput.equals("yes"))
//do your thing
}
Once the scanner input doesn't equal "yes" anymore, it will exit the while and do something else
for loops are more to iterate through a set of data, rather than a while, which is waiting for state change.
Scanner input = new Scanner(System.in);
double total;
System.out.println("Please enter your bill amount.");
double bill0 = input.nextDouble();
System.out.println("Is there another customer?");
while((String customer = input.nextLine()).equalsIgnoreCase("Yes")) {
System.out.println("Please enter their bill.");
double bill = input.nextDouble();
}
System.out.println("Okay, let's total your bill amount.");

Java tip calculator

Basically I just need help with a tip calculator program. It should ask how many customers there are, the tip percentage to be used, the bill amount of each customer, the tip amount, and the tip amount distributed evenly to each customer. I'm also trying to get the program to read in as many customers as the user wants to input for bonus to the homework. Here is the code, instead of the program returning "Please enter their bill amount" i keep getting "Is there another customer? y or n?". That is the main problem i'm having. Excuse the bad structuring, i'm basically a complete beginner.
import java.util.Scanner;
public class H3_TipCalc {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Please enter your bill amount.");
double bill = input.nextDouble();
{
String multiplecust = ("Y");
//int mc = 1;
while (multiplecust.equalsIgnoreCase("y"))
{
Scanner usrin = new Scanner (System.in);
System.out.println("Is there another customer? y or n?");
multiplecust = usrin.nextLine();
//mc++;
if (usrin.equals("y"))
{
System.out.println("Please enter their bill amount.");
}
}
}
}
}
if (usrin.equals("y"))
{
System.out.println("Please enter their bill amount.");
}
You're comparing the Scanner to "y", which is probably not what you want to compare. Compare multiplecust to "y".

How to end a while Loop via user input

package cst150zzhw4_worst;
import java.util.Scanner;
public class CST150zzHW4_worst {
public static void main(String[] args) {
//Initialize Variables
double length; // length of room
double width; // Width of room
double price_per_sqyd; // Total carpet needed price
double price_for_padding; // Price for padding
double price_for_installation; // Price for installation
String input; // User's input to stop or reset program
double final_price; // The actual final price
boolean repeat = true;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
//User Input
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
final_price = (price_for_padding + price_for_installation + price_per_sqyd)*((width*length)/9);
keyboard.nextLine(); //Skip the newline
System.out.println("The possible total price to install the carpet will be $" + final_price + "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
}
}
}
How would I make it so when the user says yes the program stop and if the user says no then the program just repeats? I don't know why I'm having so much trouble. I've searched for well over 4 hours. I am only supposed to use a while loop, I think.
You have to assign repeat in your while-loop so it becomes false if the user says yes:
repeat = !input.equalsIgnoreCase("yes");
You just need to set repeat to true or false based on user input. So in the end, compare input with yes or no. Something like this would work for you :
if ("yes".equals(input))
repeat = true; // This would continue the loop
else
repeat = false; // This would break the infinite while loop
boolean repeat = true;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
-----------------------
-------------------------
System.out.println("Do you want to continue:");
repeat = keyboard.nextBoolean();
}
you also if you want your code to be more systematic , go and search about the interrupt , specially thread interrupt , these answers above is correct , find the more organic code and implement it
You can use a break statement to exit a while loop.
while (...) {
input = ...;
if (input.equals("Y")) {
break;
}
}

Categories

Resources