Ending a for loop by pressing 'q' - java

I have been doing a project for my java class. For the project I have to have the user enter input and calculate their body mass index and body surface area the program is supposed to remain running until the user enters a "q". I cannot get my program to stop running when a "q" is put in it just crashes. Also I am very new to java and programming in general so I would appreciate any help. My code is as follows.
Thanks : )
public static void main(String[] args) {
//Scanner
Scanner stdIn = new Scanner(System.in);
//Variables
final double METERS_TO_CM = 100; // The constant to convert meters to centimeters
final double BSA_CONSTANT = 3600; // The constant to divide by for bsa
double bmi; // Body Mass Index
String weight; // Weight in kilograms
String height; // Height in meters
String classification; // Classifies the user into BMI categories
double bsa; // Body surface area
do {
System.out.print("Welcome to the BMI and BSA Calculator to begin enter weight in kilograms.");
weight = stdIn.next();
System.out.print("Enter height in meters: ");
height = stdIn.next();
double height2 = Double.parseDouble(height);
double weight2 = Double.parseDouble(weight);
bmi = weight2/(height2*height2);
if (bmi < 18.5)
{
classification = "Underweight";
}
else if (bmi < 25)
{
classification = "Normal";
}
else if (bmi < 30)
{
classification = "Overweight";
}
else
{
classification = "Obese";
}
System.out.println("Your classification is: " + classification);
bsa = Math.sqrt(((height2*METERS_TO_CM)*weight2)/BSA_CONSTANT);
System.out.printf("BMI: %.1f\n", bmi);
System.out.printf("BSA: %.2f\n", bsa);
System.out.println("Hit 'q' to quit");
} while (stdIn.nextLine().compareToIgnoreCase("q")==0);
}
}

I would guess that your "q" input is written in weight and therefore you try to parse it to a Double, which throws an unhandled Exception and stops the execution.
You should handle this Exception and make the system break the while loop when triggering it.

You're grabbing the entire line for your while loop condition.
Try just grabbing the next() instead of nextLine().
Also, you're looking at while it DOES equal 0 ... meaning equal. I'd change that to != instead. You want to continue looping while the next token is NOT Q.

Let's make a structural change to make this easier for you to do.
We are going to change it so that your do-while loop always is running, until you explicitly tell it to stop.
Your current while is:
while(stdIn.nextLine().compareToIgnoreCase("q")==0);
Which works ok, but we have a more simple way to do this. Have you heard of the break statement?
I would suggest you use break. This statement will 'break' you out of the while loop; basically it tells the program to stop looping when it is called. This will be a bit easier to follow than your somewhat confusing do-while.
do {
//Your Do code goes here, as before
...
//
//Your newly added break statement will go here.
//This breaks out of the while loop when your inputed 'choice' value is
//equal to the string of "q" (for quit)
if (Choice.equals("q"))){
break;
//When break is called nothing else in the loop will run
}
//Same thing but with the string of "quit"
if (Choice.equals("quit"){
break;
}
}while (true);
//Your new while statement is simply while(true) which will run until break is called
Hopefully that is helpful to you.

Don't actually use a loop. Since it's impractical someone would ever max the call stack out by answering too many questions, just make the whole operation a function. At the end of the function, call itself if the result isn't Q.

its simple use this
while (true)
{
Console.WriteLine("Start processing");
//processing code here
Console.WriteLine("finish processing");
Console.WriteLine("start again? y/n?");
if (Console.ReadLine().Equals("n"))
break;
}

Related

Salary calculation per hour (Java)

I've been trying to write a java program to calculate daily salary relying on hours worked per day. and if it was weekend or no. (boolean value).
The time the user need to write is 0824 it equals to 08:24 (no idea how to ask for hour:minutes pattern and subtract them).
I've been using only one loop to ask for payment Per Hour again and again if the user puts values lower than 28.00$ or higher than 100.00$.
When the program running after asking for paymentPerHour the program stops <terminated> is not shown.
Would appreciate any help. Thanks! :)
(don't pay attention to the class name)
package ouzanFirstProject;
import java.util.Scanner;
public class convertDecToBinary {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int paymentPerHour , entryHour = 0 , exitHour = 0;
float totalHour= (exitHour-entryHour)/100;
boolean workedAtWeekend;
float salary = 0;
System.out.println("Please enter the hour you arrived to work (HHMM)");
entryHour=in.nextInt();
System.out.println("Please enter the hour you exit from work(HHMM)");
exitHour=in.nextInt();
System.out.println("Please enter payment per hour (between 28.00 and 100.00):");
paymentPerHour=in.nextInt();
while(paymentPerHour>0) {
if(paymentPerHour<28 ||paymentPerHour>100) {
System.out.println("Please enter payment per hour");
paymentPerHour=in.nextInt();
}
if(paymentPerHour>=28 &&paymentPerHour<=100) {
continue;
}
}
System.out.println("Did you work on weekend ? (True/False)");
workedAtWeekend=in.hasNext();
if(workedAtWeekend){
salary= (float) ((totalHour)*0.20+100);
}
else if (totalHour>=9) {
salary=(float) ((float)(totalHour)*paymentPerHour*1.5);
if(totalHour>11) {
salary = (float)((float)(totalHour)*paymentPerHour*2);
}
}
else if(totalHour<9) {
salary=(float)((float)(totalHour)*paymentPerHour*0.1);
if(totalHour<=1) {
salary= 0;
}
if(totalHour>=15) {
System.out.println("You cant work more than 15 hours a day");
}
if(totalHour<0) {
salary=Math.abs(totalHour)*paymentPerHour;
}
}
System.out.println("You've been working for: "+totalHour+" Hours"+",And your payment is: "+salary);
}
}
You should not use continue; in the loop. It will force the loop to go to the next iteration even if the conditions are met. Instead you should use break; which will terminate the loop if the conditions are met. Also you should not add the condition paymentPerHour>0 because it will skip the loop if the user enters a negative number (thx to Idle_Mind for this one). See the code sample:
while(true)
{
if(paymentPerHour>=28 &&paymentPerHour<=100) {
break; // This will terminate the loop if the conditions are met
}
// This part will only run if the conditions are not met
System.out.println("Please enter payment per hour");
paymentPerHour=in.nextInt();
}

Why does my first input run through the do while even thought the input is 0

I am doing a school program about Casino App. First of all it is alright, but then I find out that something goes wrong with my first input. It is weird that only the first input goes wrong, others are fine. I am wondering what causes that happen and why?
public class test1
{
public static Scanner input;
public static void main(String[] args)
{
int winnings;
int bet = getBet();
do
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = bet * getPayMultiplier(thePull);
display(thePull, winnings);
bet =getBet();
}
while(bet != 0);
System.out.print("Thank you!");
}
public static int getBet()
{
final double MAX_BET = 50;
final double MIN_BET = 0 ;
String prompt, userResponse;
int Response;
do
{
prompt = "How much would you like to bet (1 - 50) or 0 to quit?";
System.out.print(prompt);
userResponse = input.nextLine();
Response = Integer.parseInt(userResponse);
}
while (Response < MIN_BET || Response > MAX_BET);
return Response;
}
My question is that when I put the first input as 0 (bet !=0 ) it shows :
How much would you like to bet (1 - 50) or 0 to
quit? 0
whirrrrrr .... and your pull is ...
BAR BAR BAR
Sorry, you lose.
How much would you like to bet (1 - 50) or 0 to
quit?
which is wrong. it should quit immediately, but if I put 0 anywhere except the first input, it works:
How much would you like to bet (1 - 50) or 0 to
quit? 1
whirrrrrr .... and your pull is ...
7 BAR cherries
Sorry, you lose.
How much would you like to bet (1 - 50) or 0 to quit? 0
Thanks for coming to Casino Loceff
Why is that?
Because do-while loop will run through the loop at least once and check the breaking condition only at the end. If you don’t want that behavior swap it for a normal while loop.
while(condition) { // your statements }
Because Response is 0. And that is not less than MIN_BET (which is 0), so the loop doesn't repeat.
Change it to <= MIN_BET, or (probably better), change MIN_BET to 1.
The problem is the usage of a do-while loop. The purpose of a do-while is to ensure the code block will always execute at least once.
The difference between a regular while and a do-while is when the expression is evaluated.
In a regular while loop the expression is checked before each loop starts. "Should I run the code?". This means that if the expression is false it will never run the block even once.
Whereas with a do-while the expression is checked after the code block executes - "Should I do this again?". So even if the expression is false the code block will be executed the first time.
Try using a regular while loop instead of do-while.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Your issue is most likely here
public static int getBet()
{
final double MAX_BET = 50;
final double MIN_BET = 1;//this should be 1 since you're asking for users to enter 1-50
String prompt, userResponse;
int Response;
do
{
prompt = "How much would you like to bet (1 - 50) or 0 to quit?";
System.out.print(prompt);
userResponse = input.nextLine();
Response = Integer.parseInt(userResponse);
//simplest way is just to add a condition here with an if statement to break the loop if the user enters 0
if(userResponse == 0){
break;
}
}
while (Response >= MIN_BET && Response <= MAX_BET);
return Response;
}

Created a two condition While loop, one condition works as should the other causes an infinite loop

so im still new to java programming and for this program i need to make a program that calculates change for a vending machine. It is based of a 5 cent increment between a value of 25 cents to a dollar. for this assignment if i use a loop to force the user to input a value in bounds i get extra credit, since i originally was going to scratch because i wasnt getting it but soon did im back to using it. only thing is for one of my conditions it creates an infinite loop of the output message and im not sure why. any advice would be appreciated
/** Carmine A
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
float changeGiven;
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
int userInput;
int itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in 5-cent increments \n"
+ "Do not enter a decimal point");
//user inputs value to be set to variable
userInput= keyboard.nextInt();
//System.out.println("You entered ." +userInput + " as the price");
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
while(userInput>25 && userInput<100){
System.out.println("Price is in bounds");
System.out.println("Please enter a valid amount between 25-100");
itemCost=keyboard.nextInt();
}
}
itemCost=userInput;
//print out item cost based off users input
System.out.println("You enetered: " + itemCost +" as the items cost");
}
}
update
ok took what you guys said and made this
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
thanks for the help! knew it was something dumb, but this is why i ask for help so i can learn
so i believe it is frowned upon if i made another thread for the same program so i will add to this one.
i have completed just about everything i need but am having a few issues.
1. for some reason after i compile and run my code "Change Due:" prints twice, i am unsure why since i only have it once in a print statement but i can be missing it.
2.i need to print out in a money format and for some reason i have tried different formatting options and none will round (i have a feeling it is but it is not displaying because of the second "Change due:" printing) but can be wrong
3. on line 55 i am receiving this message and not sure why C:\Users\finst\Desktop\Intro to Java\Labs\Lab2\lab2Test.java:55: error: incompatible types: possible lossy conversion from double to int
changeRemainder= (changeDue*(double)100);
this is what i currently have:
/** Carmine
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
double userInput;
double itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in
5-cent increments");
//user inputs value to be set to variable
userInput= keyboard.nextDouble();
//while loop to make sure input stays in bounds
while(userInput<(.25) || userInput>(1.00)){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1
dollar");
userInput=keyboard.nextDouble();
}
//print out item cost based off users input
System.out.println("You entered: " + userInput +" as the items cost");
System.out.println("You entered a dollar to pay with");
//algorithm to calculate change due
int quarters;
int nickels;
int dimes;
int pennies;
int changeRemainder;
double changeDue;
double dollar=1;
//calculates change due
changeDue= (dollar - userInput);
//System.out.printf("%.2f" + "\n" ,changeDue);
//System.out.println("Change due:" + changeDue);
//makes the remainder into a number that can be used
changeRemainder= (changeDue*(double)100);
//calculates the amount of each coin needed to make the change
quarters= (changeRemainder / 25);
changeRemainder= changeRemainder % 25;
dimes= (changeRemainder/10);
changeRemainder= changeRemainder%10;
nickels=(changeRemainder/5);
changeRemainder= changeRemainder%5;
pennies=(changeRemainder);
//output statement to print coin amounts
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
As userInput is never updated in the loop then its value does not change and it will potentially loop for ever.
Maybe you mean userInput=keyboard.nextInt(); but you do not need two loops anyway.
userInput=keyboard.nextInt();
while (userInput<25 || userInput>100) {
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
You don't need 2 while loops; just one will do. In any case, your while loop checks the 'userInput' variable, but that never changes in the while loop; you are updating the itemCost variable instead.
I would use a Boolean for your while loop, and create an if else statement within this to check for valid entry and calculate the change. Hope this helps!
boolean end = true;
while (end) {
//retrieve user input of cost and assign value to variable
//create an if statement check if the value is valid
if(itemCost >=25 && itemCost <=100){
//retrieve user input for change entered
//calculate change for the user and display it
//end loop
end = false;
} else {
//invalid entry
end = false;
}
}

If and if else again

The problem I seem to be having is that I am unsure on how to make the program recognize if the player is in one of the "MVP" positions (C,SS,CF) before moving forward with my program logic.
These three positions qualify for "MVP" status only if their OPS is above 800 for everyone else, it has to be 900 or above to be considered for "MVP".
Once again, I am having trouble with the "if" and "if else" statement.
Again, This IS school given problem and I don't want the answer. Only insight into what I am doing wrong. I want to learn this not have it done for me. Thank you in advance.
import java.util.Scanner;
public class baseBall {
public static void main(String[] args) {
/* A good part of a baseball player's offensive value is captured by the
statistic OPS - the sum of the player's on base percentage and slugging
percentage. An MVP candidate will typically have an OPS above 900,
however if they play a difficult defensive position (catcher, shortstop, or center field)
then they are an MVP candidate if their OPS is above 800. Write a program that will prompt the user for
a player's name, their on base percentage, slugging percentage, and defensive position and report whether the player is an MVP candidate*/
Scanner input = new Scanner(System.in);
System.out.println("Please enter players name: ");
String name = input.next();
System.out.println("Please enter On Base Percentage: ");
double Obp = input.nextDouble();
System.out.println("Please enter slugging Percentage: ");
double Slg = input.nextDouble();
System.out
.println("Please enter position (P,C,1B,2B,3B,SS,LF,CF,RF): ");
String ball = input.next();
String position;
double Ops = Obp + Slg;
if ( position.equalsIgnoreCase("ss")){
if (position.equalsIgnoreCase("cf")){
if (position.equalsIgnoreCase("c")){
System.out.println("MVP Candidate!");
else
System.out.println("NOT an MVP Candidate!);
}
}
}
}
}
Try doing it without nested IFs. Instead, try using Boolean operators like AND and OR.
As previously stated try using a paper first. Try drawing a decision tree to see what and where it might be going wrong.
Your code is checking if the player position is c AND ss AND cf. But the player will be only in one position, it can't be in all the three, so your code will always print "Not an MVP Candidate!".
To make it simple your code is checking if the position is c AND ss AND CF, instead you want to check if the position is c OR ss OR cf.
So you have to use the conditional operator OR -> ||:
if(position.equalsIgnoreCase("ss") || position.equalsIgnoreCase("cf") || position.equalsIgnoreCase("c") {
System.out.println("MVP Candidate!");
} else {
System.out.println("NOT an MVP Candidate!);
}
Your nested ifs will never be true. Think about this logically and on paper.
If position equals ss how can it equal cf and c at the same time? Always ask yourself: "does this make sense?" -- do this before committing code to screen and you'll be golden.
As a side recommendation, please get rid of those distracting // from your question text. They serve no purpose other than to annoy.

Break a while loop without using If or Break

I need to create a program that uses while to find the volume of a cylinder. I need the while loop to break if the user inputs a negative value for the height. My code looks like this:
double sentinel=1, h=1, v=0, r, count=0; // declares all variables needed
final double PI=3.14159;
boolean NotNegative=true;
while(NotNegative){// && count==0){ // while both the height is positive AND the total times run is 0
System.out.print("Enter height (Use negative to exit): "); // has the user input the height
h=Double.parseDouble(br.readLine());
sentinel=h; // save sentinel as the inputted height
while(sentinel>0){
System.out.print("Enter radius: "); // have the user input the radius
r=Double.parseDouble(br.readLine());
v=PI*(r*r)*h; // find the volume
System.out.println("The volume is " + v); // print out the volume
count++; // increase the count each time this runs
NotNegative=true;
sentinel=-1;
}
}
Any help?
You can throw an Exception which you catch and ignore. This is bad idea as
if and/or break is more efficient and simpler.
it's slow
it's confusing.
However, since you are using a while loop, which is like using an if & break, you can do the following.
NotNegative = h >= 0;
Add the following code inside the while(NotNegative){, after reading the input.
NotNegative = h >= 0;

Categories