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??
Related
I have written this short code and I want to let users to enter bank balance.
Then in new confirm dialog box they will choose if they want to enter transaction amount.
If "YES" then they enter either positive or negative numbers.
If entered value is negative so program with subtracts transaction amount from bank balance.
If entered value is positive so program will add transaction value to bank balance.
At the end if user selects "No" button in confirm dialog box so program will terminates with results of calculation!
Question:
when I enter numbers for bank balance and transactions so I get wrong answer!
I tried to user while loop and do while but I still get wrong results!
double total = 0;
String blc = JOptionPane.showInputDialog(null,"Enter the balance");
double balance = Double.parseDouble(blc);
int trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
while(trcsn == JOptionPane.YES_OPTION){
String transaction = JOptionPane.showInputDialog(null,"Enter amount:");
double trc = Double.parseDouble(transaction);
trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
if(trc < 0){
total = balance - trc;
}else{
total = balance + trc;
}
}
JOptionPane.showMessageDialog(null,total);
1: I enter 1000 dollars as bank balance.
2: I enter 1050 (positive) as transaction amount.
3: I enter -500 (negative value) as transaction amount for second try.
4: Answer is 1500.00 which is wrong!
1000 + 1050 = 2050.00
2050 - 500 = 1550.00
Answer should be 1550
Why answer is wrong???
In this section:
if(trc < 0){
total = balance - trc;
}else{
total = balance + trc;
}
You are updating your total, but not the balance. From the snippet you made, that remains unchanged.
As pointed out by #Fildor down in the comments below, at the moment you have a bug since you are either adding positive numbers together or else, subracting a negative number (x - (-y) == x + y)). To fix this, simply replace the entire if block with total = balance + trc.
You would need to update your balance to have the same value of total, or else, do without total altogether and use the balance field.
You should do something like the following:
String blc = JOptionPane.showInputDialog(null,"Enter the balance");
double balance = Double.parseDouble(blc);
int trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
while(trcsn == JOptionPane.YES_OPTION){
String transaction = JOptionPane.showInputDialog(null,"Enter amount:");
double trc = Double.parseDouble(transaction);
trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
balance += trc;
}
JOptionPane.showMessageDialog(null,balance);
First, you need to replace your if statement with a += statement. This is because subtracting when trc is negative and adding when trc is positive is equivalent to adding the absolute value of trc every time, which is probably not what you want to do. Second, you need to use 1 variable for balance, and track the changes over time. total is meaningless in the previous code, as it overrides its own value every time that your if statement executes.
double updatedBalance = (trc < 0) ? balance - trc : balance + trc;
total = updatedBalance;
Like the above answer suggests you need to update the balance.
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.
A real estate office handles 50 apartment units. When the rent is $600 per
month, all the units are occupied. However, for each $40 increase in rent,
one unit becomes vacant. Each occupied unit requires an average of $27 per
month for maintenance. How many units should be rented to maximize the
profit?
Write a program that prompts the user to enter:
The number of apartment Units
The rent to occupy all the Units
The increase in rent that results in a vacant unit
Amount to maintain a rented unit
The program then outputs the number of units to be rented to maximize
the profit
but I want to show to the user the rent and I don't know how
import java.util.*;
public class yeungah {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
double rent, maintenance, maintenanceCost, increase;
double result=0, profit, maxProfit = 0;
int h=0, number;
System.out.println(" enter the number of apartment units: ");
number=input.nextInt();
System.out.println( " enter the rent value for all the occupied units: ");
rent=input.nextInt();
System.out.println("The increase in rent that results in a vacant unit: ");
increase=input.nextInt() ;
System.out.println( "enter the maintain value for each occupied unit: ") ;
maintenanceCost=input.nextInt() ;
for (int i = number; i > 0; i--, rent += increase)
{
result = i * rent ;
maintenance = i * maintenanceCost ;
profit = result – maintenance ;
if (profit > maxProfit)
{
maxProfit = profit ;
h =i ;
}
}
System.out.println( "Number of units to be rented in order to maximize profit is: "+maxProfit) ;
System.out.println("It occurs when Number of occupied Units is:"+h) ;
}
}
can anyone help?
Sadly I cant make comments yet but I'm curious.
When does the for loop end? I cant see that it ever reached i>0 since i is always decreasing and I cant see that i is changed in the for loop.
I would use a while loop that breaks when profit isn't larger then maxprofit.
In the end it should be enough to take number-h to answer the assignment question
Take everything I write with a grain of salt since I'm also a rookie. :)
To show the rent after each increase do System.out.println(rent) at the end of the for loop.
To show the rent at the end you would do the same thin after the loop.
A problem I'm seeing here is that you don't seem drop out of the loop once the max profit is found. I would recommend a boolean flag. Set it to false have it as a condition along with 1 > 0.
Then within the loop add an else to your if statement setting it to true.
This will cause the loop to drop out once the max profit is found.
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;
}
}
I'm having some problems with my program, i ask the user to enter the start population,daily growth in percent, and how many days they will multiply. Then calculate the end population for each day, while making sure they are constraints to the user entered data. I keep getting back the same results for each day and the constraints aren't doing their job either.
input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
for (int days=0;days<=daysofIncrease+1;days++)
{
if (startPopulation>=2 || increase >0 || daysofIncrease>=1)
{
endPopulation=(startPopulation*increase)+startPopulation;
JOptionPane.showMessageDialog(null,"This is the organisms end population: "+endPopulation+" for day: "+days);
}
else
{
input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
}
}
}
}
Your line
endPopulation=(startPopulation*increase)+startPopulation;
Will not calculate the end population correctly. You haven't used daysofIncrease at all.
I think you'll need to loop through the days. Note that I have not tested this, may need tweaking, but it should give you the idea:
double interimPopulation = startPopulation;
for (int days=1; days<=daysofIncrease; days++) {
interimPopulation *= (1.0 + (increase/100.0)); //get next day's population
}
endPopulation = interimPopulation;
I think you need to set somewhere in your loop this:
startPopulation = endPopulation;
And then you make another iteration of the loop.
Try this for example
endPopulation=(startPopulation*increase)+startPopulation;
startPopulation = endPopulation;
And if you don't want to lose the initial value of startPopulation,
just store it somewhere, before you change it (the way I suggest).