Making piggy bank program in JAVA [closed] - java

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

Related

Change to number of coins [closed]

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.

Convertiny Monetary Units

I got the dollars to work but now I can`t figure out how to display the quarters, dimes, nickels, and pennies correctly. Technically they show up but my professor wants $1.35 to show up as 1 dollar 1 quarter and 1 dime. But, mine shows up as 1 dollars 5 Quarters 13 Dimes 27 Nickels 135 Pennies. Here is my code:
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an amount in double, for example 11.56: " );
double number = input.nextDouble();
System.out.println("Your amount " + number + " consists of ");
int remainingamount = (int)(number*100);
int Quarters = remainingamount/25;
int Dimes = remainingamount/10;
int Nickels = remainingamount/5;
int Pennies = remainingamount;
if (number == 1) {
System.out.print("1 dollar ");
}
else if (number > 1) {
System.out.print((int)number + " dollars ");
}
if (number == 0) {
System.out.println("");
}
System.out.print(Quarters + " Quarters " + Dimes + " Dimes " + Nickels + " Nickels " + Pennies + " Pennies");
}
}
For each different coin you calculate, you need to remove this from the remaining amount. Such as (untested):
int Dollars = (int)number;
int remainingamount = (int)((number-Dollars)*100);
int Quarters = remainingamount/25;
remainingamount -= Quaters * 25;
int Dimes = remainingamount/10;
remainingamount -= Dimes * 10
int Nickels = remainingamount/5;
remainingamount -= Nickels * 5
int Pennies = remainingamount;
Since you're using Java, have you tried JSR 354?
See JavaMoney.org or the JSR 354 Detail page at JCP.org It offers standard API for the conversion of monetary units and default exchange rate providers by the IMF or European Central Bank.

Java - Assigning User Input to Variable / Change Counter

I'm quite new to java, although I have a fairly basic knowledge of C++.
For my assignment I am counting change and sorting it into American currency (i.e., if you had 105 cents, it would divide it into one dollar and one dime).
Logically I understand how to do this, but I'm having some serious trouble understanding the java syntax. I'm having serious trouble to find a way to assign a user-inputted value to a variable of my creation. In C++ you would simply use cin, but Java seems to be a lot more complicated in this regard.
Here is my code so far:
package coinCounter;
import KeyboardPackage.Keyboard;
import java.util.Scanner;
public class helloworld
{
public static void main(String[] args)
{
Scanner input new Scanner(System.in);
//entire value of money, to be split into dollars, quarters, etc.
int money = input.nextInt();
int dollars = 0, quarters = 0, dimes = 0, nickels = 0;
//asks for the amount of money
System.out.println("Enter the amount of money in cents.");
//checking for dollars, and leaving the change
if(money >= 100)
{
dollars = money / 100;
money = money % 100;
}
//taking the remainder, and sorting it into dimes, nickels, and pennies
else if(money > 0)
{
quarters = money / 25;
money = money % 25;
dimes = money / 10;
money = money % 10;
nickels = money / 5;
money = money % 5;
}
//result
System.out.println("Dollars: " + dollars + ", Quarters: " + quarters + ", Dimes: " + dimes + ", Nickels: " + nickels + ", Pennies: " + money);
}
}
I would really appreciate some help with how to assign a user-input to my variable, Money. However, if you see another error in the code, feel free to point it out.
I know this is really basic stuff, so I appreciate all of your cooperation.
Change this line :
Scanner input new Scanner(System.in);
To :
Scanner input = new Scanner(System.in);
And this should be after line below not before:
System.out.println("Enter the amount of money in cents.");
And as you did , the line below will read from input int value and assign it to your variable money :
int money = input.nextInt();

min change greedy algorithm in java

Ok so i need to make a program to ask me for an amount of money, then I need it to tell me the least amount of coins to make it. The coins I can use are: dollars, quarters, dimes, nickels, and pennies. For example, When I run the program it's supposed to look like this:
> run Coins
Enter the amount of given money:
[1.73]
Give the seller 8 coins:
1 dollars,
2 quarters,
2 dime,
0 nickels,
3 pennies.
This is What I have so far:
import java.util.Scanner;
class Coins {
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
double money;
System.out.println("Enter the amount of money ");
money = input.nextDouble();
while (money > 0.0 ){
if (money >= 1) {
System.out.println(money/1+"dollars");
money -= 1;
}
else if (money>=.25) {
System.out.println(money/.25+"quarters");
money-=.25;
}
else if (money>=.10) {
System.out.println(money/.10+"Dimes");
money-=.10;
}
else if (money>=.05) {
System.out.println(money/.05+"Nickels");
money-=.05;
}
else if (money>=.01) {
System.out.println(money/.01+"Penny");
money-=.01;
}
}
}
}
The part I need help with is this: If I run the program and enter the amount 1.73, the way I have the code written, it takes the number 1.73, divides it by 1, and prints "1.73 dollars". I need a way to get rid of the decimal part so instead of printing "1.73 dollars", it prints "1 dollar". But I'm not sure how to do this. I tried converting it to an int but it messes up the flow of the other statements. Please help me.
You should use the combination of floor with casting to double, the following code works:
class Coins {
public static void main (String args[]) {
double money = 1.73;
while (money > 0.0 ){
if (money >= 1) {
System.out.println(Math.floor(money/1)+" dollars");
money -= Math.floor(money/1)*(double)1;
}
else if (money>=.25) {
System.out.println(Math.floor(money/.25)+" quarters");
money-=Math.floor(money/.25)*(double).25;
}
else if (money>=.10) {
System.out.println(Math.floor(money/.10)+" Dimes");
money-=Math.floor(money/.10)*(double).10;
}
else if (money>=.05) {
System.out.println(Math.floor(money/.05)+" Nickels");
money-=Math.floor(money/.05)*(double).05;
}
else if (money>=.01) {
System.out.println(Math.round(money/.01)+" Penny");
money-=Math.round(money/.01)*(double).01;
}
}
}
}
Another bug you had:
You should subtract Math.floor(money/XXX)*(double)XXX not (double)XXX
You need get rid of the remainder after the divisions. You can use Math.floor() for this:
class Coins {
public static void main (String args[]) {
double money = 1.73;
int dollars = (int) Math.floor(money/1);
money -= dollars * 1;
int quarters = (int) Math.floor(money/0.25);
money -= quarters * 0.25;
int dimes = (int) Math.floor(money/0.10);
money -= dimes * 0.10;
int nickels = (int) Math.floor(money/0.05);
money -= nickels * 0.05;
int pennies = (int) Math.round(money * 100);
System.out.println("Dollars: " + dollars);
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
Resulting in:
Dollars: 1
Quarters: 2
Dimes: 2
Nickels: 0
Pennies: 3

Java problem solving. Is this one right?

Merry Christmas everyone. I do have a question before Santa arrives.
I'm new with Java, so i'm skimming through my Java book and I'm doing the exercises on my first chapter.
Here's the question,
"Write and application that determines the value of the coins in a jar and prints the total in Dollars and Cents. Read integer values that represent the number of quarters, dimes, nickels and pennies."
I actually did this program. But I wonder if I did it right.
public class PP28 {
public static void main(String[] args) {
// cents = pennies.
double quarters = 0.25 * 40;
double dimes = 0.1 * 200;
double nickels = 0.05 * 400;
double pennies = 0.01 * 150;
int total;
int cent;
total = (int) quarters + (int) dimes + (int) nickels + (int) pennies;
cent = 100 % total;
System.out.println(total+" dollars and "+cent+" cents");
}
}
It compiles and runs fine. Also, I wonder if this is mathematically right? Should I get 49 cents that is almost equivalent to 51.(5)$? Because all quarters, dimes, nickels and pennies has the sum of 51.5 dollars.
I would avoid using a floating point type for this due to rounding errors.
Here is a good article explaining the issue (What Every Computer Scientist Should Know About Floating-Point Arithmetic).
Use integers to get the count in cents.
Something like this:
integer quarters = 25 * numOfQuarters;
You can get the dollar amount by diving with 100.
Oded's answer is definitely one to implement. Use integers.
You have another problem however: cent = 100 % total;
This code is not doing what you think it's doing.
Because total is an integer and is summed like this:
total = (int) quarters + (int) dimes + (int) nickels + (int) pennies;
Your result is 51. That's 51 dollars even. You lost all of the information on fractional dollars by converting the double values (quarters, dimes, nickels and pennies) to integers. If the value of quarters would have been 10.25, then (int) quarters would be 10.
Now, you are trying to get the number of leftover cents using cent = 100 % total; This gives you the integer remainder of 100 / total. In your case 100 / 51. The remainder leftover is 49 which you stored in 'cent'. It just happened in your example to be close to the correct value. This is why your answer was incorrect, not rounding.
All that said, you should STILL be using integers for all of your values.
It is easier to work on one representation, for example cents, and then later translate it into dollars. Oded's comment about floating point rounding errors are correct.
I do find it strange that you convert pennies into an integer when the value is 1.5, this doesn't seem correct. Something like this can be done instead:
int quarters = 25 * 40;
int dimes = 10 * 200;
int nickels = 5 * 400;
int pennies = 1 * 150;
int sum = quarters + dimes + nickels + pennies;
int dollars = sum / 100;
int cents = sum % 100;
When printing the values of dollars and cents I get 51 dollars and 50 cents exactly.
In addition to the problems mentioned about, the problem says read the number of quarters, dimes, nickels and pennies. That means read from a file, not have hard-coded as constants.
Also, the monetary values of quarters, dimes, nickels and pennies are unlikely to change anytime soon. They should be declared as static final variables:
class PP28 {
final int QUARTER = 25;
...

Categories