So i'm having precision issues - java

So i'm working with java on a currency denominations. the code for the most part is working just fine, but the only issue is with pennies. the problem i'm having is that it will keep leaving out 1 single penny when inputting certain amounts. Apparently we are suppose to use math.round() to convert a double value to an equivalent long value that represents cents if we want precision....but the biggest problem I have is that I dont even understand what that means let alone even understanding how to implement math.round().
We are also given this....Math.round(amount * 100). I'm not expecting any answers, but if anyone can give me any clarity or directions you can point me in. I'd gladly appreciate it, for now i'm really confused and stuck.
import java.util.Scanner;
public class MoneySorter {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
double money;
System.out.printf("");
money = stdin.nextDouble();
int hundreds, fifty, twenties, tens, fives, ones;
int quarters, dimes, nickles, pennies;
hundreds = (int) money / 100;
money = money % 100;
fifty = (int) money / 50;
money = money % 50;
twenties = (int) money / 20;
money = money % 20;
tens = (int) money / 10;
money = money % 10;
fives = (int) money / 5;
money = money % 5;
ones = (int) money / 1;
money = money % 1;
quarters = (int) (money / 0.25);
money = money % 0.25;
dimes = (int) (money / 0.10);
money = money % 0.10;
nickles = (int) (money / 0.05);
money = money % 0.05;
pennies = (int) (money / 0.01);
Some examples would be if I put in the amount: 0.99
Result:
3 Quarters
2 Dimes
3 Pennies
example 2: 127.97
1 Hundred
2 Twenties
1 Five
2 Ones
3 Quarters
2 Dimes
1 Penny

Don't declare:
double money;
...instead declare:
long money;
Then replace:
money = stdin.nextDouble();
...with:
money = Math.round(stdin.nextDouble() * 100);
Realize now that you're dealing with pennies as the main unit of currency, not dollars. This means you have to multiply much of what follows by 100. For example:
hundreds = (int) money / 10000;
money = money % 10000;
Etc., etc., until you get to:
nickles = (int) (money / 5);
money = money % 5;
pennies = (int) money;

If the application is dealing with monetary calculations, better to go with BigDecimal. BigDecimal class is for performing high-precision arithmetic which can be used in banking or financial domain based application
https://www.w3resource.com/java-tutorial/java-big-decimal-class.php
BigDecimal money;
System.out.printf("Enter the value: ");
money = new BigDecimal(stdin.nextDouble());
BigDecimal hundreds;
hundreds = money.divide(new BigDecimal(100), RoundingMode.CEILING).setScale(2);

Related

I need help making change in java. It doesnt give out change correctly

Hi I'm trying to make a method that gives you change in Hundreds, Fifties, Twenties, Tens, Fives, ones as well as quarters dimes and nickels. the user gives input and its supposed to look something like this: 6.87 1 five 1 one 3 quarters 1 dime 2 pennies
So far I have this as my code:
import java.util.Scanner;
/**
*
* #author Cjespinomartine
*/
public class Assignment04 {
public static void main(String[]args) {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter your amount");
double amount = stdin.nextDouble();
double remainder = Math.round(amount * 100);
double hundreds = remainder / 1000;
remainder = remainder / 1000;
double fifties = remainder / 500;
remainder = remainder / 500;
double twenties = remainder / 200;
remainder = remainder % 200;
/*
double fives = remainder / 5;
remainder = remainder % 5;
double ones = remainder / 1;
remainder = remainder % 1;
double quarters = remainder / .25;
remainder = remainder % .25;
double dimes = remainder / .10;
remainder = remainder %10;
double nickels = remainder / .5;
remainder = remainder % .5;
double pennies = remainder;
*/
System.out.println(hundreds + "hundred/s");
System.out.println(fifties + "fiftie/s");
System.out.println(twenties + "twentie/s");
/* System.out.println(fives + "five/s");
System.out.println(ones + "one/s");
System.out.println(quarters + "quarter/s");
System.out.println(dimes + "dime/s");
System.out.println(nickels + "nickel/s");
System.out.println(pennies + "cent/s");
*/
}
}
It doesn't give out change in order it just gives out hundreds. I commented some of the change because I'm trying to get the math right. I think the assignment required if and else if so if it does can you help me out with where I put it. any help will mean a lot i'm very stuck thank you.
There are a few things wrong.
The first issue is your initial handling of remainder – you're multiplying by 100, so if input is 1274.56, you end up with 127456 (ignoring floating point problems which are valid but I'll stay focused on this first point). The output of Math.round() is either an int or long, but definitely not a double so you're adding confusion for yourself by storing it as a double – instead, store the result as long. From there, when you calculate hundreds, you need to divide by 10,000 not 1,000. Also, store that as an int, not a double. Here's what that would look like:
long remainder = Math.round(1274.56 * 100);
int hundreds = (int) remainder / 10000;
System.out.println("hundreds: " + hundreds);
The above prints out "12" for hundreds, which is what you want.
The second issue is how you're calculating remainder. You want everything that's "left over" from the prior calculation which you do by using % (modulus operator), and also use 10,000 instead of 1,000. For the hundreds case, it would be this:
remainder = remainder % 10000;
System.out.println("remainder: " + remainder);
The above code would print this:
remainder: 7456
This should give you enough to get the rest of your math working properly.
remainder = remainder / 1000; is wrong. What you want is the remainder after you've taken out all the hundreds. remainder = remainder % 1000; -looks like the commented out ones are correct...
Also don't use floating point types for money. Google will give you a thousand reasons why.

How to determine the fewest number of each different coin needed to represent that entered amount?

I am very new to programing, and I am having trouble with this program which wants the user to enter a number of "alien coins" called novas and then determines the fewest number of each different alien coin needed to represent that amount, starting with the highest. Here are the coins and what they are worth:
1 aurora = 60 pulsars
1 pulsar = 70 gravitons
1 graviton = 6 novas
Here is a sample input and output on how it should look:
Enter number of novas: 64197 [Enter]
That number of novas is equal to:
2 auroras
32 pulsars
59 gravitons
3 novas
This is my code:
import java.util.Scanner;
public class AlienMoney {
public static void main(String[] args){
int startAmount, amount, auroras, pulsars, gravitons, novas;
Scanner input = new Scanner(System.in);
System.out.print("Enter number of novas: ");
amount = input.nextInt();
System.out.println("That number of novas is equal to: ");
startAmount = amount;
gravitons = amount / 6;
amount = amount % 6;
pulsars = amount / 70;
amount = amount % 70;
auroras = amount / 60;
amount = amount % 60;
novas = amount;
System.out.println(auroras + " auroras");
System.out.println(pulsars + " pulsars");
System.out.println(gravitons + " gravitons");
System.out.println(novas + " novas");
}
}
And this is my output:
Enter number of novas: 64197 [Enter]
That number of novas is equal to:
0 auroras
0 pulsars
10699 gravitons
3 novas
I am not sure what I am doing wrong. I know I definitely have to use the modulus operator % to get the remainder, but I am not sure what to do after that. I would greatly appreciate anyone's help. Thank you.
You need to calculate your currencies in the correct order, starting from the largest.
So:
aurora > pulsar > graviton > nova
Instead of:
graviton > pulsar > aurora > nova
The approach in the code snippet below is to compute the number of novas in each of the three coins, and then to calculate how many of each coin to use to represent the amount entered.
In order to use the fewest number of coins, we should begin by using as many auroras as possible, with the remainder as pulsars, followed by gravitons last.
int auroras = amount / (6 * 70 * 60);
int remainder = amount % (6 * 70 * 60);
int pulsars = remainder / (6 * 70);
remainder = remainder % (6 * 70);
int graviton = remainder / 6;
int novas = remainder % 6;
Right here, problem lines indicated in comments:
startAmount = amount;
gravitons = amount / 6;
amount = amount % 6;
pulsars = amount / 70; // <-- starts here
amount = amount % 70;
auroras = amount / 60;
amount = amount % 60;
novas = amount;
You're using the wrong variables. Use the variables you assigned the needed amount into instead, e.g.:
startAmount = amount;
gravitons = amount / 6;
amount %= 6;
pulsars = gravitons / 70;
gravitons %= 70;
auroras = pulsars / 60;
pulsars %= 60;
novas = amount; // this doesn't need to change but there's no need to assign amount into a new variable
Also use the %= operator. It's pretty cool. ;)

Making piggy bank program in JAVA [closed]

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

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

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