Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to get the minimum amount of coins(quarters, dimes, nickels and pennies) needed to meet a stated amount of change(1-99). Example:
Change: 93
Quarters: 3
Dimes: 1
Nickels: 1
Pennies: 3
When I run my program, I don't get the answers that I'm supposed to. My question is how do I make the output in my program look like the solution above? Do I change the equations within the program to get the numbers I want? The only part of the program I have right is the amount of quarters needed to meet the stated amount. This program also needs to work for ANY stated amount between 1 and 99.
Here's what I have so far:
package mincoins;
import java.util.Scanner;
public class MinCoins2
{
public static void main(String[] args)
{
int change = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
try ( //creates a copy of Scanner class
Scanner in = new Scanner(System.in))
{
System.out.println("Please enter amount of change(1-99)");
change = in.nextInt();
//loop for quarters
while (change >= 25)
{
change = change - 25;
quarters = quarters + 1;
}
while (change >= 10)
{
change = change - 10;
dimes = dimes + 1;
}
while (change >= 5)
{
change = change - 5;
nickels = nickels + 1;
}
pennies = change;
System.out.println("Change: " + change);
System.out.println("Quarters = " + change);
System.out.println("Dimes = " + change);
System.out.println("Nickels = " + change);
System.out.println("Pennies = " + change);
}
}//end of main
}//end of class
You have typos on the last 4 lines:
System.out.println("Change:" + change);
System.out.println("Quarters= "+ change);
System.out.println("Dimes=" + change);
System.out.println("Nickels=" + change);
System.out.println("Pennies=" + change);
Are all printing change
Also, the while loop conditions should be >= instead of >.
Lastly, to print out the change at the end, you have to copy it, since you're modifying it in your while loops.
change = in.nextInt();
int changeOut = change;
...
System.out.println("Change:" + changeOut);
Live Demo
Obviously the typo is the problem, needs to be:
System.out.println("Quarters = " + quarters);
System.out.println("Dimes = " + dimes);
System.out.println("Nickels = " + nickles);
System.out.println("Pennies = " + change);
But I want to make a suggestion about how this code works W.R.T. to the loops, e.g.:
//loop for quarters
while (change > 25) {
change = change - 25;
quarters = quarters + 1;
}
This is easily done without a loop:
quarters = change / 25;
change = change - quarters * 25;
This is because change and 25 are ints, so / will do an integer division. It will give the largest number of quarters that fit in the change, i.e. it's rounding down.
Going one step further you can also use the % modulo operator to get the remaining change at each step:
quarters = change / 25;
change = change % 25;
dimes = change / 10;
change = change % 10;
nickels = change / 5;
change = change % 5;
The main problem is the variables you're using. You should be using your quarters, dimes, nickels, and pennies variables in the appropriate spots.
There's another logical error - you need to exhaust all of the leftover change to comprise your pennies count. Since your output (the one you actually require) doesn't mandate that you count the change left over (since it should be 0), you can avoid another loop altogether and just directly assign pennies to change:
pennies = change;
...and this will give you the right result for the total number of pennies left over.
As some general cleanup, you would also want to avoid assigning in the print statement, as it can be a bit confusing. Use statements such as change -= 25 independent of the System.out.println instead.
Related
I'm trying to write a program that outputs the change of a payment in dollars, quarters, dimes, etc. I declare all the coin variables at the beginning of the program, but don't initialize them, and I get this error when I try to initialize them later in the program. So, I just initialized them to 0 to initialize them and then it doesn't recognize that I'm changing the values and they stay at 0.
import java.util.Scanner;
public class ChangeClient {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int dollars = 0;
int quarters = 0;
int dimes = 0;
int nickles = 0;
int pennies = 0;
double change = 0.0;
double newChange = 0.0;
System.out.println("How much was it? ");
double cost = kb.nextDouble();
System.out.println("What did you pay with? ");
double payment = kb.nextDouble();
if(payment-cost == 0) {
change = 0.0;
}
else {
change = payment - cost; //4.73
newChange = change;
if((newChange-change != 0 && newChange >= 1)) {
dollars = (int)(change/1);//dollars = 4
newChange = (change - dollars);// newchange = .73
}
if((newChange - change) != 0 && newChange >= .25) {
quarters = (int)(newChange/.25); //quarters = 2
newChange = (change - (dollars + (quarters*.25))); //newchange = 4.73 - (4+ (2*.25)) = .23
}
if(newChange - change != 0 && newChange >= .10){
dimes = (int)(newChange/.10); //dimes = 2
newChange = (change -(dollars + (quarters * .25) + (dimes * .10))); //newchange = 4.73 - (4+ (2*.25) + (2*.10)) = .03
}
if(newChange - change != 0 && newChange >= .05) {
nickles = (int)(newChange/.05);
newChange = (change -(dollars + (quarters * .25) + (dimes * .10) + (nickles * .05))); //newchange is less than .05 so skip
}
if(newChange - change != 0 && newChange >= .01) {
pennies = (int)(newChange/.01); //pennies = 3
newChange = (change -(dollars + (quarters * .25) + (dimes * .10) + (nickles * .05) + (pennies * .01))); //newchange (4.73 - (4 + (2*.25) + (2 .10) + (3*.03))) = 0
}
System.out.println("Dollars: " + dollars);
System.out.println("Quarters: " + quarters);
System.out.println("Dimes " + dimes);
System.out.println("Nickles " + nickles);
System.out.println("Pennies " + pennies);
System.out.println("Total change due: " + change);
}
}
}
I know there are a ton of people who get errors like this and I've looked through all of them to find a solution, but none of them were the same as the problem I'm having.
I think the problem is this here:
` newChange = change;
if((newChange-change != 0 && newChange >= 1)) `
if you set newChange to change, then newChange-change will always be 0.
So you all of your if-statements will evaluate to false.
For the precision problem:
An easy solution would be to multiply the inputs with 100 and work with integers. Just think of handling cents instead of Dollars ;-)
Your problem is with this assignment:
newChange = change;
Followed these comparisons:
if ((newChange - change) != 0 && newChange >= .25)
if (newChange - change != 0 && newChange >= .10)
etc...
You initialize newChange = change, so newChange - change will always equal zero and all of your if blocks will be skipped.
A few more notes:
-Consider using the debug mode of your IDE. You can set a breakpoint and see the values of variables as your program executes each line. Java has fantastic debugging (including remote debugging). Here's how your program looks in my IDE (Eclipse Neon):
-A full-featured Java IDE (the big two are Eclipse and IntelliJ, though NetBeans has at least one devotee at my office) leverages many of the features of compile-time type-safety, debugging, and Java conventions. You can rename a variable or method throughout an application with a single operation, you can see whether a method you are trying to call exists, you can even call a method that doesn't exist yet and let the IDE stub it out for you. All these are possible because the IDE is constantly compiling the code in the background as you write it, so it knows every place a class, variable, or method is used. Debugging allowed me to find the error in your code in (I kid you not) 10 seconds. This is why we write Java for enterprise-grade applications!
-Consider using the objects Double and Integer instead of instead of the primitive types double and int, and use the comparison .equals(). In the object-oriented world, we prefer to abstract out the implementation of a comparison from the comparison itself. Consider this example:
Double first = 3.5;
Double second = 3.5;
boolean equal = (first == second); // false
In this example, Java compares the pointers to first and second, which point to different locations in memory (because each variable has its own space allocated in memory and first and second are just references to those locations).
This refactor will have the expected behavior in all cases:
Double first = 3.5;
Double second = 3.5;
boolean equal = first.equals(second); // true
The authors of the Double class have implemented a .equals() method that ensures the comparison is of the values, not the references. This is another strength of OO programming; you can #Override a default .equals() method and implement your own based on whatever criteria you want. This is useful if, for example, you want two class instances to be considered equal based on just one or two of their fields. In your case, using double primitives, it's certainly not critical to use .equals(), but it is a good habit to get into or you will run into surprises with the String class and others.
Good luck!
I've corrected your code.
import java.util.Scanner;
public class ChangeClient {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int dollars;
int quarters;
int dimes;
int nickles;
int pennies;
double change;
double newChange;//no need of newChange
System.out.println("How much was it? ");
double cost = kb.nextDouble();
System.out.println("What did you pay with? ");
double payment = kb.nextDouble();
if(payment-cost == 0) {
change = 0.0;
}
else {
change = payment - cost; //4.73
if(change >= 1) {
dollars = (int)(change/1);//dollars = 4
change = (change - dollars);// change = .73
System.out.println("Dollars: " + dollars);
}
if(change >= .25) {
quarters = (int)(change/.25); //quarters = 2
change = (change - quarters*.25); //change = .73-2*.25 = .23
System.out.println("Quarters: " + quarters);
}
if(change >= .10){
dimes = (int)(change/.10); //dimes = 2
change = (change -dimes * .10); //change = .23-2*.10 = .03
System.out.println("Dimes " + dimes);
}
if(change >= .05) {
nickles = (int)(change/.05);
change = (change -nickles * .05); //change is less than .05 so skip
System.out.println("Nickles " + nickles);
}
if(change >= .01) {
pennies = (int)(change/.01); //pennies = 3
change = (int)(change -pennies * .01); //change = .03 - 3*.01 = 0
System.out.println("Pennies " + pennies);
System.out.println("Total change due: " + change);
}
}
}
}
newChange which you have used is wrong as pointed out by others and you wont even need it. If you go through my corrections, I've used change itself to be used throughout. Hope this helps.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have been away from Java for awhile and am trying to recall and learn a lot still. I have a current project which is a piggy bank that you add coins to and can get various outputs. I am currently tasked with 5 methods plus a helper method for the constructors. I know what I want to do, but can't think through the code to get it done. I want to use the helper method to get the amounts for the other two constructors, but cannot get my head around it, I can only look through my book so long. Any input is appreciated.
The description for each method is as follows:
P.S. The code I do have may not be correct.
publicChangeJar() Default constructor that sets all the instance variables to zero
publicChangeJar(int quarters, int dimes, int nickels, int pennies) A constructor that initializes the instance variables with the provided values converted to quarters, dimes, nickels, and pennies.
public ChangeJar(final double amount) A constructor that initializes the instance variables with the provided value converted to quarters, dimes, nickels, and pennies. For example, if amount was 1.34 then you would have 5 quarters, 1 nickel, 4 pennies
public ChangeJar(final String amount)A constructor that accepts a string as a parameter with the provided value converted to appropriate number of quarters, dimes, nickels, and pennies. For example, if amount was “1.34” then you would have 5 quarters, 1 nickel, 4 pennies.
public ChangeJar(final ChangeJar other)A constructor that initializesthe instance variables of “this” ChangeJar object with the other object.
public class ChangeJar {
private int pennies;
private int nickels;
private int dimes;
private int quarters;
static boolean globalLock = false;
public ChangeJar(){
this(0,0,0,0);
}
public ChangeJar(int pennies, int nickels, int dimes, int quarters)throws IllegalArgumentException {
if (pennies < 0 || nickels < 0 || dimes < 0 || quarters < 0)
throw new IllegalArgumentException("You cannot have negative coins in the jar");
else this.pennies = this.pennies + pennies;
this.nickels = this.nickels + nickels;
this.dimes = this.dimes + dimes;
this.quarters = this.quarters + quarters;
}
public ChangeJar(double amount){
}
public ChangeJar(final String amount){
}
private double amountHelper(double amount){
amount = pennies*.01 + nickels*.05 + dimes*.10 + quarters*0.25;
return amount;
}
public ChangeJar(final ChangeJar other){
}
}
EDIT: My problem here is how to write the helper method to work in both constructors.
Constructor ChangeJar(double)
For your constructor with an amount, you want to use the maximum number of quarters, then the maximum number of pennies, and so on.
Let's say I have $2.87.
First, I will take 11 quarters. We still have $0.12 left.
Then, I will take 1 dime. We still have $0.02 left.
Then, I will take 0 nickel. We still have $0.02 left.
Then, I will take 2 pennies. We're done.
How to implement that? Let's say the amount is 2.87.
public ChangeJar(double amount) {
// How many quarters?
int quarters = (int) (amount / .25); // The division gives 9.48 and we cast the result to int so we get 9
amount = amount - quarters * .25;
System.out.println(quarters + " quarters. Remains: " + amount);
// How many dimes?
int dimes = (int) (amount / .10);
amount = amount - dimes * .10;
System.out.println(dimes + " dimes. Remains: " + amount);
// How many nickels?
int nickels = (int) (amount / .05);
amount = amount - nickels * .05;
System.out.println(nickels + " nickels. Remains: " + amount);
// How many pennies?
int pennies = (int) (amount / .01);
amount = amount - pennies * .01;
System.out.println(pennies + " pennies. Remains: " + amount);
// Prints:
// 11 quarters. Remains: 0.1200000000000001
// 1 dimes. Remains: 0.0200000000000001
// 0 nickels. Remains: 0.0200000000000001
// 2 pennies. Remains: 1.0061396160665481E-16
// Now we just set this in our properties:
this.quarters = quartes;
this.dimes = dimes;
this.nickels = nickels;
this.pennies = pennies;
}
As you can see, the problem is that the remainders are strange values. The constructor works but it's not really cool. Why? Because Java approximates the doubles.
I would suggest to work with ints. For example, you could change your unit from $ to $/100. Our same example with integer values (the input is not 2.87 but 287):
public ChangeJar(int amount) {
// How many quarters?
int quarters = amount / 25;
amount = amount - quarters * 25;
System.out.println(quarters + " quarters. Remains: " + amount);
// How many dimes?
int dimes = amount / 10;
amount = amount - dimes * 10;
System.out.println(dimes + " dimes. Remains: " + amount);
// How many nickels?
int nickels = amount / 5;
amount = amount - nickels * 5;
System.out.println(nickels + " nickels. Remains: " + amount);
// How many pennies?
int pennies = amount;
amount = amount - pennies;
System.out.println(pennies + " pennies. Remains: " + amount);
// Prints:
// 11 quarters. Remains: 12
// 1 dimes. Remains: 2
// 0 nickels. Remains: 2
// 2 pennies. Remains: 0
// Now we just set this in our properties:
this.quarters = quartes;
this.dimes = dimes;
this.nickels = nickels;
this.pennies = pennies;
}
That's already better!
But there is a lot of copy/paste in my code...
How could we make it better?
We can see that for each coin, I get the number of coins and then I subtract the value from the amount.
int amount = 287;
int[] values = new int[]{25, 20, 5, 1}; // The values of my coins
int[] results = new int[values.length];
for (int i = 0; i < values.length; i++) {
int valueOfCoin = values[i];
int numberOfCoins = amount / valueOfCoin; // Division gives the integer part of the result
results[i] = numberOfCoins;
amount = amount % valueOfCoin; // Modulo gives the remainder part of the result
// Or you could simply write: amount %= valueOfCoin;
}
System.out.println("RESULTS=" + Arrays.toString(results));
// Prints:
// RESULTS=[9, 1, 0, 2]
Constructor ChangeJar(String)
I suppose that the String is an amount so we will just convert the String to a Double and call the other constructor (ChangeJar(double)).
public ChangeJar(String amount) {
this(Double.valueOf(amount)); // Double.valueOf() will try to convert the String => Double
}
Constructor ChangeJar(ChangeJar)
The idea is just to copy the values of the other ChangeJar:
public ChangeJar(ChangeJar other) {
this(other.quarters, other.dimes, other.nickels, other.pennies);
}
I'm having an issue with a change machine I'm building for my Java class. I'm very new to programming so this may be a dumb logic error. My change machine asks the user to input the price of the item then amount paid then it is supposed to calculate how much change the user will receive in quarters, dimes, etc... However, it's only counting 1 quarter each time. Here's the code:
import java.util.Scanner;
import java.text.*;
public class Main {
public static void main(String[] args)
{
float penny = .1F, nickel = .5F, dime = .10F, quarter = .25F;
int pennyCtr = 0, nickelCtr = 0, dimeCtr = 0, quarterCtr = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
float price = scan.nextFloat();
DecimalFormat paidFormat = new DecimalFormat("0.00");
System.out.println("Enter Amount Paid: ");
float paid = scan.nextFloat();
float change = (float) (paid - price);
System.out.println("Your change from $" + paidFormat.format(paid)
+ " is: " + change);
if (change >= .25)
{
change -= quarter;
quarterCtr++;
}
else if (change < .25)
{
change -= dime;
dimeCtr++;
}
else if (change < .10)
{
change -= nickel;
nickelCtr++;
}
else if (change < .5)
{
change -= penny;
pennyCtr++;
}
System.out.println("Your change from $" + paidFormat.format(paid) +
" is: " + quarterCtr + " Quarters, " + dimeCtr + " Dimes, "
+ nickelCtr + " Nickles, " + pennyCtr + " Pennies. ");
System.out.println("Program written by Ashley ");
}
}
Some general hints:
Look at how you are declaring your variables, especially penny and nickel.
Look at how you are calculating change. Is that right?
You need a while loop. How long should it loop for? When should the loop end?
When you print out "Your change from...", consider how you could output the change neatly.
Google some questions about float subtraction - it's not as easy as it first seems! Consider using double instead for your declarations and input.
A quick look at the code tells me that you are missing a loop between this block of code:
if (change >= .25)
{
change -= quarter;
quarterCtr++;
}
else if (change < .25)
{
change -= dime;
dimeCtr++;
}
else if (change < .10)
{
change -= nickel;
nickelCtr++;
}
else if (change < .5)
{
change -= penny;
pennyCtr++;
}
Essentially, your program will terminate before it can reduce the change to 0. This is why you are only counting 1 coin every time. Consider maybe a while loop (while change > 0) perhaps.
I'm working on a program that will calculate the basic interest accrued on a certificate of deposit. The program asks for the amount of money invested and the term (up to five years). Depending on how many years their term is, is what determines how much interest is earned. I use an if/else statement to determine the rate of interest. I then use a loop to print out how much money is in the account at the end of each year. My problem is that when I run the program, the money is not counting.
Here is the entire code.
import java.util.Scanner;
public class CDCalc
{
public static void main(String args[])
{
int Count = 0;
double Rate = 0;
double Total = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("How much money do you want to invest?");
int Invest = userInput.nextInt();
System.out.println("How many years will your term be?");
int Term = userInput.nextInt();
System.out.println("Investing: " + Invest);
System.out.println(" Term: " + Term);
if (Term <= 1)
{
Rate = .3;
}
else if (Term <= 2)
{
Rate = .45;
}
else if (Term <= 3)
{
Rate = .95;
}
else if (Term <= 4)
{
Rate = 1.5;
}
else if (Term <= 5)
{
Rate = 1.8;
}
int count = 1;
while(count <= 5)
{
Total = Invest + (Invest * (Rate) / (100.0));
System.out.println("Value after year " + count + ": " + Total);
count++;
}
}
}
and here is the result I get with a 10 dollar investment, just to keep it simple, and a 5 year investment.
How much money do you want to invest?
10
How many years will your term be?
5
Investing: 10
Term: 5
Value after year 1: 10.18
Value after year 2: 10.18
Value after year 3: 10.18
Value after year 4: 10.18
Value after year 5: 10.18
My main problem is I dont know how to make it continually add the intrest onto the total. I'm not sure if I need to use a different loop or what. Any help would be appreciated.
Total = Invest + (Invest * (Rate) / (100.0));
You are not changing the value of Invest for each year, so it is not compounding. It is like you are getting .18$ of interest each year, retired from the account.
Change Total for Invest.
You need to add the investment interest to your total:
Total = Invest;
int count = 1;
while(count <= 5)
{
Total = Total + (Invest * (Rate) / (100.0));
System.out.println("Value after year " + count + ": " + Total);
count++;
}
public String convertHeightToFeetInches()
{
int leftOver = heightInInches % IN_PER_FOOT;
if(heightInInches < (IN_PER_FOOT * 2)){
return "1 foot " + leftOver + " inches";
}
else{ return "";
}
if(heightInInches < (IN_PER_FOOT * 3) && heightInInches > (heightInInches * 2)){
return "2 foot " + leftOver + " inches";
}
else{
return "";
}
I want to make it return "1 foot 4 inches" or however tall they are..
I got the first if statment to work but what would i do to continue up to like 6 feet.. I tried just adding another one but im pretty sure thats not how to do it. How can i put this together?
Wouldn't it be simpler just to calculate the foot as well?
public String convertHeightToFeetInches()
{
int inches = heightInInches % IN_PER_FOOT;
int foot = heightInInches / IN_PER_FOOT;
return "" + foot + " foot and " + inches + " inches";
}
It's possible to use a division statement to come up with the number if feet in 'heightInInches'.
Can you try that?
For example, I'm confident that if I know someone is 50 inches tall, I can quickly calculate that the person is at least 4 feet tall.
Once you have that working, we'll work on the inches.
You have most of the logic correct as it is, but you do need a little push. Consider a height between 1 and 2 feet. In mathematical terms, we would describe this as 1 < x <= 2. Consider now what that would translate to in Java - what about x must be true? Hint: it's two conditions.
Next, an if-else if-else won't work if you have an else just sitting there. else will execute if nothing else matches with it (and that will occur often). Place an if after those elses.