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

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

Related

While-loop equals to not working properly (java bank account)

So my task is to write a bank-account program that asks wether you want to deposit or withdraw money, it asks for how much and at last if I want to continue or not, and if not it will show my current account balance. Example:
Deposit or withdraw (0-deposit, 1-withdraw):
How much?
Do you want to continue?
Balance: XX.XX
The program should be looped and break when the answer is "Y" on "Do you want to quit?".
package Account;
import java.util.Scanner;
public class bankVisit {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
bankAccount account = new bankAccount();
String respond = "N";
System.out.print("Deposit or withdraw (0-deposit, 1-withdraw): ");
int choice = scan.nextInt();
while (respond.equals("N")) {
if (choice == 0) {
System.out.print("Amount: ");
double total = scan.nextDouble();
account.credit(total);
System.out.print("Do you want to quit? ");
respond = scan.next();
} else if (choice == 1) {
System.out.print("Amount: ");
double total = scan.nextDouble();
account.withdraw(total);
System.out.print("Do you want to quit? ");
respond = scan.next();
}
System.out.print("Deposit or withdraw (0-deposit, 1-withdraw): ");
choice = scan.nextInt();
}
System.out.println("Balance: " + account.getBalance());
scan.close();
}
}
I get it to loop, but I dont get how I should make the loop to quit, and post my balance, it keeps looping even though "respond" not equals "N".. Any ideas? Im very new to Java so anything will do.

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

Tip Calculator statement confusion

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)

Allow Java to recognize input not equal to a wanted value

I am new to both Java and this site so please have mercy on any mistake I may make, I am at my wits end!
I am trying to make a program that calculates the speed of sound through different mediums. As of now the program will ask the user for input on the distance and allow input, same for the medium. I created several cases that will calculate the the answer of the given medium which work properly.
The issue is when I try to create a loop that recognizes if the medium input is not one of the 4 options available. I was able to successfully create a loop that recognizes if the distance input is not a numeric value and tried using similar principles for the medium input but either keep getting stuck in infinite loops or getting the message I created for a wrong entry when I entered the right option.
I have tried the basic loops that I have been taught: for, do-while, etc., but am stuck. Any and all suggestions are appreciated, thank you so much!
public static void main(String[] args) {
//prompt the user about the purpose of this program
System.out.println(" The purpose of this program is to calculate the speed of sound through several mediums.\n The program user will input a distance in feet followed by a mediums and the program will output the speed in feet per second and miles per hour\n");
//declare variables
Scanner keyboard = new Scanner(System.in);
final double Air = 1126.1;
final double Water = 4603.2;
final double Steel = 20013.3;
final double Earth = 22967.4;
double OneFootPerSecond = .68181818182;
double Distance;
double AirSpeed;
double WaterSpeed;
double SteelSpeed;
double EarthSpeed;
System.out.print(" What is the distance in feet:" );
//ask the user to input variables
while (!keyboard.hasNextDouble()){
System.out.println("Please enter a valid numeric value, try again: ");
keyboard.next();
}
Distance =keyboard.nextDouble();
{
System.out.print("Input the media: Air, Water, Steel, or Earth: ");
String Input = keyboard.next();
Input.toLowerCase();
switch (Input)
{
case "air":
AirSpeed = Distance/Air;
System.out.print("\n \nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through AIR" +"\n");
System.out.printf("%.6f", AirSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Air);
System.out.print(" miles per hour.");
System.out.print("\n \nEnter Yes for another calculation, else No: ");
String Another = keyboard.next();
Another.toLowerCase();
break;
case "water":
WaterSpeed = Distance/Water;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through WATER" +"\n");
System.out.printf("%.6f",WaterSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Water);
System.out.print(" miles per hour.");
break;
case "steel":
SteelSpeed = Distance/Steel;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through STEEL" +"\n");
System.out.printf("%.6f",SteelSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Steel);
System.out.print(" miles per hour.");
break;
case "earth":
EarthSpeed = Distance/Water;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through EARTH" +"\n");
System.out.printf("%.6f",EarthSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Earth);
System.out.print(" miles per hour.");
break;
First of all, as suggested in the comment, change Input.toLowerCase(); to something like:
Input = Input.toLowerCase();
or change switch(Input) to:
switch(Input.toLowerCase())
Now to the fun part...
Instead of a case of a new word, add a default: block. This will be run, if nothing else is matched.
switch (Input)
{
case "air":
AirSpeed = Distance/Air;
System.out.print("\n \nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through AIR" +"\n");
System.out.printf("%.6f", AirSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Air);
System.out.print(" miles per hour.");
System.out.print("\n \nEnter Yes for another calculation, else No: ");
String Another = keyboard.next();
Another.toLowerCase();
break;
// Some more cases...
default:
// Something something that will happen as a "last resort".
break;
} // End switch
No problem.
I see the following Problem:
Input.toLowerCase();
is not working use
Input=Input.toLowerCase();
because the function just return a new String

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