Coin Change calculation [duplicate] - java

This question already has an answer here:
Need help making my first Java code. (Coin Change) [duplicate]
(1 answer)
Closed 6 years ago.
My assignment requires me to read a number entered by the user and output the coins that number makes. For example, if the user enters "37", the program should respond with (1 Quarter, 1 dime, and 2 pennies).
This is the code I've gotten so far I would appreciate it if someone could help me finish it as well as see if my current code has any errors
import java.util.Scanner;
public class Coin
{
Scanner sc = new Scanner (System.in);
Int n = sc.nextInt("Enter a positive integer" );
int number1, number2; // Division operands
int quotient; // Result of division
public static int getQuarters(int cents) {
return Math.floor(cents / 25.0);
}
public static int getDimes(int cents) {
return Math.floor(cents / 10.0);
}
public static int getNickels(int cents) {
return Math.floor(cents / 5.0);
}
public static int getPennies(int cents) {
return Math.floor(cents / 1.0);
}
public static void main(String[] args) {
int cents = 46;
int left = cents;
int quarters = getQuarters(cents);
int left -= quarters * 25;
int dimes = getDimes(left);
left -= dimes * 10;
int nickels = getNickels(left);
left -= nickels * 5;
int pennies = left;
System.out.println(cents + " cents = " + quarters + " Quarters, " + dimes + " Dimes, " + nickels + " Nickels, and " + pennies + " Pennies."); // print the output
}
}

First, "if my current code has any errors" - Yes, it does, and your development environment should point them out. Or if you're using a command-line build, again, it would point them out. The one that jumps out at me: you have a second definition of "left". But the point is, let your IDE or build-script tell you if you have any syntax errors.
Then, to address "could help me finish it" I ask: have you even tried running it? (Well no, it won't compile with the second "int left" definition). But clean up the errors, run it and see what happens...You just might be surprised.
Of course, then you need to activate the input scanner instead of hard-coding the amount to calculate...

The follwing can be used ,but I don't quite understand your variables.
import java.util.Scanner;
public class Test{
public static int getQuarters(int cents) {
return (int) Math.floor(cents / 25.0);
}
public static int getDimes(int cents) {
return (int) Math.floor(cents / 10.0);
}
public static int getNickels(int cents) {
return (int) Math.floor(cents / 5.0);
}
public static int getPennies(int cents) {
return (int) Math.floor(cents / 1.0);
}
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter a positive integer");
int n = sc.nextInt();
// int number1, number2; // Division operands
// int quotient; // Result of division
int cents = n;
int left = cents;
int quarters = getQuarters(cents);
left -= quarters * 25;
int dimes = getDimes(left);
left -= dimes * 10;
int nickels = getNickels(left);
left -= nickels * 5;
int pennies = left;
System.out.println(cents + " cents = " + quarters + " Quarters, " + dimes + " Dimes, " + nickels + " Nickels, and " + pennies + " Pennies."); // print the output
}
}

Related

converting money into all possible combinations

I know my question is repeated but I still couldn't understand what the other answers are explaining. Below is my code and I have calculated it to get to the first line which is 57 pennies + 0 dimes + 0 nickels + 0 quarters and I am thinking to run a loop that will list all the possible combinations of pennies, dimes, nickels, quarters. But, I don't know how.
public class Conversion{
public static void main(String[] args) {
int cents = 57;
int quarter = 25;
int dime = 10;
int nickel = 5;
int penny = 1;
int totalPennies = cents / penny;
cents %= penny;
int totalNickels = cents / nickel;
cents %= nickel;
int totalDimes = cents / dime;
cents %= dime;
int totalQuarters = cents / quarter;
cents %= quarter;
System.out.print(totalPennies + " pennies + ");
System.out.print(totalNickels + " nickels + ");
System.out.print(totalDimes + " dimes + ");
System.out.println(totalQuarters + " quarters");
}
}
Your order of operations is backwards.
The first thing you do is count how many pennies you have. Since pennies are literally valued at 1, you can have 57 pennies and make up $0.57 just fine. That is obviously not what you want to accomplish.
What you want to do is count from your highest denomination and work your way backwards. Here's a sample.
// This should be the first operation
int totalQuarters = cents / quarter;
cents %= quarter;
I leave reordering the rest as an exercise for the reader, but the output then becomes correct once successfully reordered.
2 pennies + 1 nickels + 0 dimes + 2 quarters

How to use int output to calculate other output?

Create a Change application that prompts the user for an amount less than $1.00 and then displays the minimum number of coins necessary to make the change.
The change can be made up of quarters, dimes, nickels, and pennies.
Here is what I did:
public static void main(String[] args) {
System.out.println("Enter the amount in cents: ");
int a = in.nextInt();
if(a <= 100){
}else{
System.out.println("Try Again");
System.exit(0);
}
{
int q = (a/25);
int d = (a/25);
System.out.println("Quarters: " + q);
System.out.println("Dimes: " + d);
}
}
}
D is irrelevant. because I don't know how to get the remainder of quarters and divide it by 10 and so on all the way through pennies
To find the remainder of anything, subtract off the amount you've taken.
For free, you need to subtract off the coin price times the amounts as you go.
if(a <= 100){
int q = a/25;
a = a-q*25;
int d = a/10;
a = a-d*10;
}

why does it print twice? if -else [duplicate]

This question already has answers here:
Java - Looping 2d Array to find index of a value not working
(2 answers)
Closed 7 years ago.
I'm learning java atm , and had to write a code to calculate the monetary units, and only display the nonzero denominations using singular words for single units and plural words for plural units.
This is the code so far:
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
// receive amount
System.out.println("Enter an amount in double, for example 11.56: ");
double amount = input.nextDouble();
int remainingAmount = (int)(amount * 100);
// find the number of one dollars
int numberOfDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
// find the number of quarters in the remaing amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
//find the number of dimes in the remaing amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
//find the number of nickels in the remaing amount
int numberOfNickles = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
//find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
//Display results
System.out.println("Your amount" + amount + "consists of");
if (numberOfDollars > 1) {
System.out.println(" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1); {
System.out.println(" " + numberOfDollars + "dollar");
}
The output is:
run:
Enter an amount in double, for example 11.56:
12,33
Your amount12.33consists of
12dollars
12dollar
1quarters
1quarter
0dimes
0dime
1nickles
1nickle
3pennies
3penny
Why is everything printed double? 3 == not 1 so why does it still say 3 penny?
Noob question maybe, but thats because i am one :) Thanks for help!
Because you added a random ; after the second if. Therefor your second System.out.println is not part of the if-statement. Remove it:
if (numberOfDollars > 1) {
System.out.println (" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1) {
System.out.println (" " + numberOfDollars + "dollar");
}
Remove the semicolon after if();
if (numberOfDollars == 1);
The second print statement is printing because it is not a part of if(); due to the semicolon that you have after if()
replace
else if (numberOfDollars == 1); { // with ;, condition terminates here itself
with
else if (numberOfDollars == 1) {
Semicolon at the end of If statememnt , finish the statement in single line. Means it ignores the result of condition and continue the execution from the next line.

My loop is wrong. Brand new to Java. Any insight as to where I am going wrong? I am supposed to calculate coins

I am working on a project that calculates the number of coins used to produce a certain total of change. For some reason, my output is only reading this:
Quarters:
Dimes:
end.
It doesn't print the integer being calculated, and does not continue past dimes. I have tried using different loops and print statements, but am at a loss. Any insight of hints would be greatly appreciated.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minimumcoinsproject;
import java.util.Scanner;
/**
*
* #author user
*/
public class MinimumCoinsProject {
/**
*
* #author
*/
static public class MinumimCoinsProject//a class is not an object, but a blueprint for an object. It is the building blocks.
{
}
public static void main(String[] args) {
// TODO code application logic here
{ //initialization
int change = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
Scanner in;
in = new Scanner(System.in);
System.out.println("Lets calclulate the minimum coins.\n");
System.out.println("PLease enter amount of change.(1-99)\n");
change=in.nextInt(); //asks for the amount of change to calculate
//start of while loop
while ( change >= 25)
{
quarters = quarters+1;
change = quarters - 25;
System.out.printf("Quarters:\n", quarters);
}
if (10 >= change)
{
dimes = dimes + 1;
change = change - 10;
System.out.printf("Dimes: \n", dimes);
}
if (change >=5)
{
nickels = nickels + 1;
change = change - 5;
System.out.printf("Nickles: \n",nickels);
}
if ( change == 0)
System.out.printf("Pennies: \n", change);
}
}
}
First while loop :
change = quarters - 25;
should be
change = change - 25;
Then the three if loops should also be while loops.
I think this should work:
int change = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
Scanner in;
in = new Scanner(System.in);
System.out.println("Lets calclulate the minimum coins.\n");
System.out.println("PLease enter amount of change.(1-99)\n");
change=in.nextInt(); //asks for the amount of change to calculate
//start of while loop
while ( change >= 25)
{
quarters = quarters+1;
change = change - 25;
}
System.out.printf("Quarters:\n"+quarters+"\n");
while (change>=10)
{
dimes = dimes + 1;
change = change - 10;
}
System.out.printf("Dimes: \n"+dimes+"\n");
while(change>=5)
{
nickels = nickels + 1;
change = change - 5;
}
System.out.printf("Nickles: \n"+nickels+"\n");
if ( change>0)
System.out.printf("Pennies: \n"+change+"\n");
Change:
System.out.printf("Quarters:\n", quarters);
To this:
System.out.printf("Quarters:%d\n", quarters);
Do the same for dimes, nickels, pennies.
I looked further and found some more issues with your code.
This should get it working:
while (change >= 25) {
quarters = quarters + 1;
change = change - 25;
}
if (quarters > 0) {
System.out.printf("Quarters:%d\n", quarters);
}
if (change >= 10) {
dimes = dimes + 1;
change = change - 10;
System.out.printf("Dimes:%d\n", dimes);
}
if (change >= 5) {
nickels = nickels + 1;
change = change - 5;
System.out.printf("Nickles:%d\n", nickels);
}
if (change > 0) {
System.out.printf("Pennies:%d\n", change);
}

Change Machine Math & Logic Errors

I've posted this program once before but realized I was overthinking it by adding loops and what not. I've paired it down a bit but still running into problems. The program is supposed to be a change machine. After the user inputs price, the program should round it up to the nearest dollar then output how much change will be dispensed and a count of which coins. The output is completely wrong at this point. I'm very new to programming and I'm at a loss.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price*100);
int paid = (int)(newPrice+1);
int change = (int)(paid - newPrice);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Once newPrice is an int, you can stop casting every line.) Instead of chaining % together, it would be more readable (and less error prone) to subtract off the values you've found:
change -= 25*quarters;
dimes = change / 10;
change -= 10*dimes;
nickels = change / 5;
change -= 5*nickels;
pennies = change;
I think it would help you to understand if you would go through the code by hand and think about what price, newprice, paid, and change are.
newprice is the price round down to the lower dollar.
paid is the cost of the item.
change is the amount you paid minus the cost converted into an integer number of pennies.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price);
int paid = (int)(newPrice+1);
int change = (int)((paid - price) * 100);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
If instruction int paid= (int)(newPrice+1) ; is supposed to be rounding to next dollar, then it should be: int paid= ( newPrice + 99 ) / 100 * 100 ; You don't need to convert to (int) when both operands are already ints. Makes your program slightly illegible. Later, after obtaining the number of quarters by quarters= change / 25 ;(that's correct in your program), you can reduce the amount fromchangewithchange-= quarters * 25 ;`.
This makes calculating dimes exactly the same as quarters, just that using 10 instead of 25. Don't forget reducing the dimes from the pending change again with change-= dimes * 10 ;. You can repeat the process with nickels and the remaining change will be pennies.
If you have any doubt, use a debugger or output each intermediate result with System.out. You can always delete them later once you understand your program's behavior.
This is how I made Java choose what coins I must pay with.
int temp = m;
int quarterCoin = 25;
int x = m/quarterCoin;
m=m-x*quarterCoin;
int dimeCoin = 10;
int z = m/dimeCoin;
m=m-z*dimeCoin;
int nickelCoin = 5;
int y = m/nickelCoin;
m=m-y*nickelCoin;
int pennyCoin = 1;
int w = m/pennyCoin;
m=m-w*pennyCoin;
Instead of giving you the answer/solution to your homework, I am going to help you figure out how to figure it out. :)
In order to adequately debug your software and troubleshoot what's going on, you need to know what your variables are doing. There are two methods:
Attach a debugger - Most IDEs will come with a debugger that will help you accomplish this.
Print out your variables to the console. This is my preferred method. Me and debuggers never have gotten along well together. :)
So, here is what I would do if I were trying to figure your program out:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter Purchase Price: ");
double price = 5.65d;//scan.nextDouble();
int newPrice = (int) (price * 100);
System.out.println("newPrice: " + newPrice);
int paid = (int) (newPrice + 1);
System.out.println("paid: " + paid);
int change = (int) (paid - newPrice);
System.out.println("change: " + change);
int quarters = (int) (change / 25);
int dimes = (int) ((change % 25) / 10);
int nickels = (int) ((change % 25 % 10) / 5);
int pennies = (int) (change % 25 % 10 % 5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Note: Instead of utilizing the scanner, I just manually entered "5.65" into the price variable just to save time)
Which produces the output:
newPrice: 565
paid: 566
change: 1
Dispensing: 0 Quarters,0Dimes,0Nickels,1Pennies.
Program written by Ashley
So, now you can see what your program is doing wrong. Can you spot it?

Categories

Resources