Program getting stuck in while loop? - java

I need to write a program that calculates beverages for an entered amount of money. It was working before but I don't know if NetBeans just got tired of doing stuff or what because it suddenly couldn't get past the inputs. I can't figure out what I need to change to get it to function properly again and I can only assume it's the while loop that it's getting stuck on.
I have tried changing numbers, deleting spaces, altering the while conditions, moving line breaks around, and nothing works. Here is the official question:
Johnny is at the bar and he is going to drink beer.
Write a program that computes how many beers he can buy for money that he has. The program reads the amount and the price of beer, and prints how many beers he can afford. Consider also tax (10%) and tips (20%). Print the result in the following form: If a beer costs $3.25, Johnny can have 3 beers for $15 (he will pay $12.87).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double br;
double amt;
double taxPrc;
double bill;
int count = 0;
System.out.printf("enter ur name: ");
String name = sc.nextLine();
System.out.printf("Enter price of beverage: $");
br = sc.nextDouble();
System.out.printf("Enter amt %s has: $", name);
amt = sc.nextDouble();
taxPrc = br * 1.1;
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
System.out.printf("if bevergae costs $"+br+", "+name+" can have "+count+" beverges for $"+amt+" (the bill will be $"+bill+").");
System.out.println();
}
My editor isn't showing that there are any problems. The file runs:
"enter ur name (name), Enter price of beverage $(#), Enter amt (name) has $(input number)"
then it just stops showing anything and leaves me on a blank until I stop it.
It's supposed to go on "if beverage costs $X, [name] can have [#] beverages for $[#] (the bill will be $[#])."
I was having an issues trying to get it to display the correct number for the bill less than the initial amount entered when it stopped working.

Just think about this block of code on its own for a bit
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
?
What in the while loop changes either bill or amt? Remember, a while loop runs until something in its conditional statement (in this case bill<amt) changes. As nothing in the while loop changes anything in the condition statement, it runs forever.
Your code doesn't change amt at all and just keeps resetting bill to the same value.

Related

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

My code is not working well

import java.util.Scanner;
public class NewClass {
public static void main(String[]args){
Scanner input=new Scanner(System.in);
String productMin="";
System.out.print("How much money do you have? ");
double money=input.nextDouble();
double minPrice=0;
double total=0;
double productPrice;
System.out.print("Please, insert the items in the invoice (the
name of product and its price):\n Insert \\\"stop\\\" as the name of
product to finish your input \n");
String productName=input.next();
productPrice=input.nextDouble();
total=total+productPrice;
while(!input.next().equals("stop"))
{
if(minPrice<productPrice)
{
minPrice=productPrice;
productMin=productName;
}
productName=input.next();
total=total+productPrice;
}
if(total<=money)
{
System.out.println("You have enough money !");
System.out.printf("%s is the item with the minimum price(which is SR
%.3f)\n",productMin,minPrice);
}
else
System.out.println("You don\'t have enough money");
System.out.println(total);
}//end of main method
}//end of calss
This is my code and it is not giving me the minimum price of the product and its name I tried a lot of things but still nothing and I'm running out of time can someone tell me where is the mistake????
This how the output should be
How much money do you have? 100
Please, insert the items in the invoice (the name of product and its price): Insert \"stop\" as the name of product to finish your input
Banana 20.200
Water 15.300
Honey 37.500
stop
You have enough money
Water is the item with the minimum price (which is KD 15.300)
And this my output
How much money do you have? 100
Please, insert the items in the invoice (the name of product and its price):
Insert \"stop\" as the name of product to finish your input
ss 20.100
dd 15.200
ff 37.500
stop
You have enough money !
ss is the item with the minimum price(which is SR 20.100)
in this line
while(!input.next().equals("stop"))
what happens if the user did not enter stop? - he/she still entered something...
You simply forgot to take the product price as an input in your while loop, you are taking it as a string.

program quitting before its meant to be finnished

So im making a program for an assesment acts as a vending machine, asks you how many cans you would like to purchase and then calculates the values, asks for coins input (assuming the user is being sensible) and then tries to calculate the change given.
The problem i am running in to is that after the program reads in the values for the payment and calculates if it is enough with the following:
double coins[] = new double[]{2.00,1.00,0.50,0.20,0.10,0.05};
//A while loop so that it continues to go until the payment is equal or more than the cost
int count2 = 1;
while (payment <= totalCost){
if (payment == totalCost){
System.out.println("You have entered the exact amount of change! Thankyou.");
break;
}
System.out.println("Please enter more coins: ");
coinsIn[count2] = kbd.nextDouble();
payment = payment + coinsIn[count2];
count2++;
}
It just ends the program.
The problem is, that directly after that while loop i have this sample of code
double change = payment - totalCost;
int count3 = 0;
if ((change == coins[count3]) && (count3 <6)) {
System.out.println("Your change is: ");
System.out.println(change);
}
else{
count3++;
}
That should run, but just doesn't.
For instance say the total cost is $4.50 and i enter in 2 x 2.00 and 1x 1.00 it should run through that if loop and find that in the coins[] there is a .50 value at coins[2], then print the message for the change and then quit.
This is the working example in the terminal:
Please enter the amount of cans that you would like to purchase:
1
Please enter the amount of cans that you would like to purchase:
1
Please enter the amount of cans that you would like to purchase:
1
There are currently [297] cans remaining.
The total cost of your purchase is [$4.5].
Please enter your payment now:
2.00
Please enter more coins:
2.00
Please enter more coins:
1.00
It just ends right after that 1.00,
I do not understand what is going on here.
Any help would be much appreciated.
P.S. Everything compiles fine.
Try changing the initialization of count3 variable. Are you sure with the usage of count3??

Can't understand this scanner or addition command

I'm very new to Java and don't quite understand it all fully, I'm working on a Uni workshop assignment but am having trouble with this particular question.
"Write a program that asks the user to enter how many minutes they have used, and how many texts they have used.
Both inputs should be whole numbers (integers).
The program should then calculate the user’s mobile phone bill, assuming that texts cost 7p and calls 12p.
Should display price of calls, texts and the total bill, both figures added together"
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
String one = userInput.nextLine();
System.out.println("How many texts have you used?");
String two = userInput.nextLine();
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+one);
System.out.println("The total cost of you texts is "+two);
System.out.println("The total cost of your phone bill is "+one + two);
I have the basic part to the question figured out, but can't figure out why I can't add to the code for it to figure out the price, being 12 p for minutes, and 7p for texts. As well as this I can't get the total cost of the phone bill to add together correctly. I did earlier and I know it's very easy, but I've completely forgotten how to do it.
I know I need to be able to understand a scanner better, but I did the previous tasks easy enough but this has really stumped me tbh. Do I need to rename the scanner, but when I change the name of the integer line to something like "totalCostOfTexts/Minutes etc" it either says it has already been defined, or is missing some kind of symbol.
Any feedback is appreciated.
I add the code :
int = userInput = minutes * 12:
As that's what is used in the previous part of a similar question, but all the feedback I get is that it is not a statement, so it can't process. I'm really struggling with this tbh.
Following code will work for you
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = userInput.nextInt();
System.out.println("How many texts have you used?");
int two = userInput.nextInt();
int a = 12; //don't use such variable names
int b = 7;
int minute_bill=12*a; //see the variable,will make things easier to review
int text_bill=7*b;
int result=minute_bill+text_bill;
System.out.println("The total cost of your minutes is "+minute_bill);
System.out.println("The total cost of you texts is "+ text_bill);
System.out.println("The total cost of your phone bill is "+result);
and also
You can use Scanner's nextInt() method for taking integer input
from console.
Don't use such variable names like a,b etc. define them according to the attribute whose value you are storing in them (see above minute_bill and text_bill are making the code clean and easy to review)
And if you are bound to get String value from console,but want to convert entered value to Integer later on, then you can do it like following code
String mystring=userInput.nextLine(); //userInput is user Scanner's object
int num=Integer.parseInt(mystring);
I think this is what you want to do...
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = Integer.valueOf(userInput.nextLine());
System.out.println("How many texts have you used?");
int two= Integer.valueOf(userInput.nextLine());
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+ (one * 12);
System.out.println("The total cost of you texts is "+ (two * 7));
System.out.println("The total cost of your phone bill is "+ ((one * 12) + (two * 7));

Shipping Program

So I seem to have put together majority of this program correctly. Ask I skim through I realized I missed something and go back and add it in. Now as I run the program for a final test I realize that it is no longer calculating the miles correctly. I input 500 for example and will get 1 in return for number of miles shipped.
input = JOptionPane.showInputDialog("Enter package weight: ");
weight = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter approximate miles package is being shipped: ");
miles = Integer.parseInt(input);
miles = (miles+499)/500;
input = JOptionPane.showInputDialog("Enter number of units shipped: ");
units = Integer.parseInt(input);
I know I am not doing the math correctly in order to find the correct amount charged per unit but what is concerning for now is the miles being shown incorrectly in my output. Any suggestions? Thanks!
Assuming miles is declared as double (if it's not, you should declare it as double so you can assign it a real number). This line
miles = (miles+499)/500;
is making a integer division (int/int = int). To get a double, you must cast it:
miles = (double)(miles+499)/500;
or, as #Vulcan suggested
miles = (miles+499)/500.0; // here 500.0 is a double
It seems like the data type of miles variable is int.Please change it to double and re-run the application.
Also as per ur comment updating the logic :
Let the input you entered is :
double weight = 7; //input
double miles = 550; //input
double unit = 2; //input
double charges =0; //charge of the shipment initialise with 0
charges = (3.70*miles*unit*weight)/(500*7);
System.out.println("The charges is "+charges);
The charges of 1 unit is $3.70 per 7 pound weight per 500 miles.
Also update the existing code :
miles = Integer.parseInt(input); //Use double as conversion
miles = (miles+499)/500; // remove the line

Categories