min change greedy algorithm in java - 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

Related

Trouble with the converting units

I am having a hard time understanding how to convert amounts such as $1.17 into this output:
1 dollar,
1 dime,
1 nickel,
2 pennies.
I need to use if statements which I can figure out but, the problem i am having is trying to get the change amounts to display correctly. Here is my code. I`m a visual learner so if you start me in the right direction that would be helpful.
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 Dollars = (int) (number);
int Quarters = Dollars / 25;
if (number == 1) {
System.out.print("1 dollar ");
}
else if (number > 1) {
System.out.print((int)Dollars + " dollars ");
}
if (number == 0) {
System.out.println("");
}
System.out.print( Quarters + " Quarters ");
}
}
You will probably want to use the modulus operator %. It is used with 2 numbers and returns the remainder of a divided by b where a is the left hand assignment and b is the right hand represented like a%b.
Example:
11%2=1 explanation: 5*2 = 10, 11-10 = 1
.66%.25=.16 explanation: 2*.25 = .5, .66-.5=.16
Start with a simple problem where you only have 2 types of coins, say 8ยข or $0.08.
double monies = .08;
int numNickles = (int)(monies/.05) = 1 // one nickle
monies = monies % .05; // or you can write as monies %=.05;
// monies value should now be .03
int numPennies = (int)(monies/.01) = 3 // three pennies
A much simpler approach than using modulus is to calculate the units of measurement in top-down fashion (from the highest to the lowest) and keep deducting them from the total already converted into the lowest unit.
A lot of libraries use this approach with units of time as well i.e. converting a time span into hours, minutes and seconds. Here's the same approach for currency. I've added inline comments to explain the code as best as possible.
// Scan the amount
Scanner scanner = new Scanner(System.in);
System.out.print("Enter amount: ");
double amount = scanner.nextDouble();
scanner.close();
// convert into cents
int cents = (int) (amount * 100);
// get dollars
int dollars = cents/100;
// cents left after dollars
cents = cents - dollars*100;
// get quarters
int quaters = cents/25;
// cents left after quarters
cents = cents - quaters*25;
// get dimes
int dimes = cents/10;
// cents left after dimes
cents = cents - dimes*10;
// get nickels
int nickels = cents/5;
// cents left after nickels
cents = cents - nickels*5;
// leftover cents are pennies
int pennies = cents;
Now, just build the output message with a StringBuilder as
StringBuilder msg = new StringBuilder("You have:");
if (dollars > 0) {
msg.append(" ").append(dollars).append(" dollar").append(dollars > 1 ? "s" : "");
}
if (quaters > 0) {
msg.append(" ").append(quaters).append(" quarter").append(quaters > 1 ? "s" : "");
}
if (dimes > 0) {
msg.append(" ").append(dimes).append(" dime").append(dimes > 1 ? "s" : "");
}
if (nickels > 0) {
msg.append(" ").append(nickels).append(" nickel").append(nickels > 1 ? "s" : "");
}
if (pennies > 0) {
msg.append(" ").append(pennies).append(" pennie").append(pennies > 1 ? "s" : "");
}
System.out.println(msg);
Output :
Enter amount: 1.17
You have: 1 dollar 1 dime 1 nickel 2 pennies
Enter amount: 12.99
You have: 12 dollars 3 quarters 2 dimes 4 pennies

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

Change Machine Only Counting Quarters

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.

calculating interest on a certificate of deposit

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

Categories