how to exchange an amount of money into notes and coins - java

how can I exchange a given amount of money into notes and coins? lets say input is 1234,26
and we have notes for 1000, 500, 200, 100, 50, and coins for 20, 10, 1, and 0.5? so if input is greater than .25 and less than .75 it should be rounded to 1x 0.5 if its between .75 and 1.00 it should be rounded to 1x 1 and if its less than .25 it should be rounded to nothing?¨
for this exact program the desired output would look something like this:
1x: 1000
1x: 200
1x: 20
1x: 10
4x: 1
1x: 0.5
if it wasnt for the 0.5 coin, I think I would have been able to do it using int and %, but as of right now I am pretty much clueless(think I have to use array, but im not sure how) and have no idea how to start. also im beginnner, if you can keep that in mind as well when answering and explaining! any tips/solutions? thanks in advance!
like this?:
System.out.println((input/1000) + " thousand " + ((input/500)%2) + " fivehundred " + (input/200%2.5) + " two hundred " + (input/100%2) + " hundred " + (input/50%2) + " fifty " + (input/20%2.5) + " twenty " + (input/10%2) + " ten " + input/1%10 + " one " );
still not sure how to deal with the 0.5 since I have to use int, input only cuz if I use double I get it completely wrong, I also have to use a if statement for the 0.5 coin..

I believe this is the standard approach to this kind of question.
double input = 1234.26;
int thousands = input/1000;
input = input - 1000*thousands; //So now it would 234,26
int fivehundreds = input/500;
input = input - 500*fivehundreds;
etc...
Right, but you can't convert from double to int (i.e. thousands is an int, but input is a double, so input/1000 is a double). So you have a few options:
Make thousands, fivehundreds, etc... be double. That is kinda ugly, though, there's no way they will have any decimal valu
Casting mean anything to you? For example, (int)int thousands = input/1000; will work. You can read up on "casting", but basically I'm just telling Java to treat that number as an int, not a double
Keep input as a int, and round it down. Then just check at the end if it has a decimal value (input % 1 > 0), and if it does, you need a half dollar.

Related

find the difference between a negative and positive number

I have a value stored in my db.table as arrears which has a minus sign eg arrears = -100.0 and when an amount is to be paid to cancel or reduce the arrears, am getting wrong results. eg:
arrears = -100.0 is displayed in a jtextfiled named 'arrears' from db.table
user inputs amount to be paid into a textbox named 'pay'.
a calculation must be done and new arrears must be entered back into 'arrears' jtextfield.This is the code I wrote below:
double a,b,e;
a=Double.valueOf(arrears.getText());
b=Double.valueOf(pay.getText());
e=a+b;
arrears.setText(String.valueOf(e));
arreas= -100.0, amount paid = 50.0 after the calculation I get answer as -45.0 instead of -50. please what is the problem.
It is look like problem isn't in a calculation. I recommend you using debugger or logging, for example:
double a,b,e;
System.out.println("arrears = " + arrears.getText());
System.out.println("pay =" + pay.getText());
a=Double.valueOf(arrears.getText());
b=Double.valueOf(pay.getText());
e=a+b;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("e = " + e);
arrears.setText(String.valueOf(e));
User enters 5 in pay text field—> 5 is added to arrears, user enters 0 into pay text field —> 50 is added and total value is now -100 + 5 + 50 = 45

Converting user input from binary to decimal using Modulus Operator in Java

I am having a hard time figuring out the answer to a homework assignment for Programming 1 class. The assignment is prompt a user for input (up to 4 bits) in binary, and convert it to the decimal equivalent. Using loops, conditional statements, ParseInt, and anything other than the modulus operator and other math operators are not allowed.
I am having trouble with the mathematical aspect, I think once I understand how to use the modulus operator to answer the question I would be able to write the code for it.
I have searched and have not been able to find anything that was able to help.
You should be getting the number values of each position and add them using the power of 2 to get back the original number.
double num = 1110;
double ones = Math.floor(num % 10);
double tens = Math.floor(num/10 % 10);
double hundreds = Math.floor(num/100 % 10);
double thousands = Math.floor(num %10000 /1000);
double tenThousands = Math.floor(num / 10000 % 10);
double original = (ones * 1) +
(tens * 2) +
(hundreds * 4) +
(thousands * 8);
System.out.println(num);
System.out.println("ones: " +ones);
System.out.println("tens: " +tens);
System.out.println("hundreds: " +hundreds);
System.out.println("thousands: " + thousands);
System.out.println("original number : " + original);

How do I use "BigDecimal" in Java for my specific code?

I'm very new to programming in Java. I have been given an assignment in my school to solve the following exercise:
"Create two variables, each containing a number. Put out a message that shows how often the second number fits into the first one, and the rest (if there is one)" [I hope the wording is clear. I'm translating this from my native language german into english]
Now in general, I have solved the exercise like this (using Netbeans):
double numberOne = 10, numberTwo = 35.55;
double result, rest;
String conversion, numberOutput;
result = numberTwo / numberOne;
conversion = Double.toString(result);
int indexOfComma = conversion.indexOf(".");
numberOutput = conversion.substring(0, indexOfComma);
rest = numberTwo % numberOne;
System.out.println("The second number fits " + numberOutput +
" times into the first one. The rest is: " + rest);
With the numbers provided, the system pops out this message:
"The second number fits 3 times into the first one. The rest is: 5.549999999999997"
I don't like the rounding error for the rest. I expected it to give out "5.55" like a human would type or write it. After a bit of googling around it seems that something called "BigDecimal" is the solution to my problem, but the explanations I found of how to implement this in Java go wayyy over my head.
Would you be so kind as to show me exactly where and how I need to use BigDecimal in the above code to get the desired output? I would also be happy to see any alternative solutions you can think of.
BigDecimal version of your code:
BigDecimal numberOne = new BigDecimal("10");
BigDecimal numberTwo = new BigDecimal("35.55");
BigDecimal[] divRem = numberTwo.divideAndRemainder(numberOne);
System.out.println("The second number fits " + divRem[0].stripTrailingZeros().toPlainString() +
" times into the first one. The rest is: " + divRem[1].stripTrailingZeros().toPlainString());
Output
The second number fits 3 times into the first one. The rest is: 5.55
You can use BigDecimal like
BigDecimal a = BigDecimal.valueOf(10);
BigDecimal b = BigDecimal.valueOf(35.55);
BigDecimal c = b.divide(a, 3, BigDecimal.HALF_UP);
System.out.println(b + " / " + a + " = " + c);
Or you could use rounding like
System.out.printf("(int)(%.2f / %d) = %d%n", 35.55, 10, (int) (35.55 / 10));
System.out.printf("%.2f %% %d = %.2f%n", 35.55, 10, 35.55 % 10);
which prints
floor(35.55 / 10) = 3
35.55 % 10 = 5.55

Why is it adding the variables wrong?

I'm using Java but, it's not adding the amount correctly. I'll give my parts of my code.
final double taxrate=.08;
Map<String,Integer> Priceproduct= new HashMap<String,Integer>();
Priceproduct.put("shoes",(int) 50.00);
Priceproduct.put("shirts",(int) 30.00);
Priceproduct.put("shorts",(int) 75.00);
Priceproduct.put("caps",(int) 15.00);
Priceproduct.put("jackets",(int) 100.00);
System.out.print("\n Enter the product: ");
String product=keyboard.nextLine();
System.out.print( "\n Enter the quantity of the product");
int quantity=keyboard.nextInt();
int cost= Priceproduct.get(product)*quantity;
int tax= (int) (cost*taxrate);
System.out.print("\n tax=" +cost*taxrate+"");
int TotalBill= cost+tax;
System.out.print("\nTotal="+cost+ + +tax+"");
When it adds the cost and tax (those two are correct) it's gets the completely wrong answer.
For example 3 shirts= 90, the tax equals 7.2, and the total becomes 907.
Do I need to use DecimalFormat or something else?
Change this:
System.out.print("\nTotal="+cost+ + +tax+"");
to this:
System.out.println();
System.out.print("Total=" + (cost + tax));
(The problem is that + is left-associative, so without parentheses around your addition, "a" + b + c means ("a" + b) + c, which does string-concatenation at both stages.)
When you perform an operation alongside a string Java will perform that operation as if the operands were strings.
In your System.out.println() calls you don't need to redo the calculations, just print out the variables "tax" and "totalBill". (This will solve the problem of printing '907')
You will only ever get integer values because you are using int type for everything. If you want to have decimals to indicate cents you should be using type double.

O Notation Help

I am getting stuck with the class work we got this week and its a subject i really want to learn so for once i thought i would do the additional reading!!!!
The method is provided for us and i am just writign some test cases. This is where my knowledge gets a little hazy. If the time increases then i am underestimatign the complexity i believe? in this case n^3 isnt enough and n^4 is too much, hence the gradual reduction to 0.
That means there is a compelxity that lies between the 2, and this is where log n comes in as log n is a value less than n? but this is as far as my knowledge goes
i was really hoping someone could clear this confusion up for me with a better explanation than whats on the lecture slides as they make no sence to me at all, thanks
/**
* Number 5
*/
public int Five(int n)
{
int sum=0;
for(int i=0; i<n; i++){
for(int j=0; j<i*i; j++){
sum++;
}
}
return sum;
}
public void runFive()
{
// Test n^2 complexity
// System.out.println("We are passing the value 5, This returns us an n value of " + Five(5) + " , With a time complexity of " + complexityN2(Five(5), 5) + " This is to test the value of 5 in a n^2 test" );
// System.out.println("We are passing the value 10, This returns us an n value of " + Five(10) + " , With a time complexity of " + complexityN2(Five(10), 10) + "This is to test the value of 10 in a n^2 test" );
// System.out.println("We are passing the value 100, This returns us an n value of " + Five(100) + " , With a time complexity of " + complexityN2(Five(100), 100) + "This is to test the value of 100 in a n^2 test" );
// System.out.println("We are passing the value 1000, This returns us an n value of " + Five(1000) + " , With a time complexity of " + complexityN2(Five(1000), 1000) + "This is to test the value of 1000 in a n^2 test" );
// System.out.println("We are passing the value 10000, This returns us an n value of " + Five(10000) + " , With a time complexity of " + complexityN2(Five(10000), 10000) + "This is to test the value of 10000 in a n^2 test" );
// Test n^3 complexity
// System.out.println("We are passing the value 5, This returns us an n value of " + Five(5) + " , With a time complexity of " + complexityN3(Five(5), 5) + " This is to test the value of 5 in a n^3 test" );
// System.out.println("We are passing the value 10, This returns us an n value of " + Five(10) + " , With a time complexity of " + complexityN3(Five(10), 10) + "This is to test the value of 10 in a n^3 test" );
// System.out.println("We are passing the value 100, This returns us an n value of " + Five(100) + " , With a time complexity of " + complexityN3(Five(100), 100) + "This is to test the value of 100 in a n^3 test" );
// System.out.println("We are passing the value 1000, This returns us an n value of " + Five(1000) + " , With a time complexity of " + complexityN3(Five(1000), 1000) + "This is to test the value of 1000 in a n^3 test" );
// System.out.println("We are passing the value 10000, This returns us an n value of " + Five(10000) + " , With a time complexity of " + complexityN3(Five(10000), 10000) + "This is to test the value of 10000 in a n^3 test" );
//
//Test n^4 complexity
System.out.println("We are passing the value 5, This returns us an n value of " + Five(5) + " , With a time complexity of " + complexityN4(Five(5), 5) + " This is to test the value of 5 in a n^3 test" );
System.out.println("We are passing the value 10, This returns us an n value of " + Five(10) + " , With a time complexity of " + complexityN4(Five(10), 10) + "This is to test the value of 10 in a n^3 test" );
System.out.println("We are passing the value 100, This returns us an n value of " + Five(100) + " , With a time complexity of " + complexityN4(Five(100), 100) + "This is to test the value of 100 in a n^3 test" );
System.out.println("We are passing the value 1000, This returns us an n value of " + Five(1000) + " , With a time complexity of " + complexityN4(Five(1000), 1000) + "This is to test the value of 1000 in a n^3 test" );
System.out.println("We are passing the value 10000, This returns us an n value of " + Five(10000) + " , With a time complexity of " + complexityN4(Five(10000), 10000) + "This is to test the value of 10000 in a n^3 test" );
}
Here are the complexity Methods
public double complexityN2(double time, double n)
{
return time / (n * n);
}
public double complexityN3(double time, double n)
{
return time / (n * n * n);
}
public double complexityN4(double time, double n)
{
return time / (n * n * n * n);
}
public double complexityLog(double time, double n)
{
return time / (Math.log(n) * (n*n));
}
Keep in mind that big-O notation describes the behavior as the number of items approaches infinity. As such, you shouldn't expect to see an exact fit when dealing with almost any practical amount of computation. In fact, you don't necessarily see an exact fit under any circumstances -- it may approach a fit asymptotically, but even when (from a practical viewpoint) the number involved is really large, it's still not a very close fit. For as small of numbers as you're using for part of your test (e.g., 5, 10, 100) the fit will often be extremely poor even at best.
From a viewpoint of timing, most implementations of Java make life substantially more difficult as well. The problem is that most JVMs will interpret the first few (where "few" is rather loosely defined) iterations of some code, before they decide it's being executed often enough to be worth compiling to more optimized machine code. The numbers you're using are almost certainly small enough that in some cases you're timing interpreted code and in others compiled code (and somewhere in there, getting an execution that includes the time taken to compile the code as well). This has no real effect on the accuracy of big-O notation, but (especially for small number) can and will have a substantial effect on how closely your timing comes to fitting what big-O would predict.
The only question-mark in your question appears at the end of this sentence:
That means there is a compelxity that lies between the 2, and this is where log n comes in as log n is a value less than n?
That sentence is not a question, it is a statement: what are you asking here?
If you are asking what log(n) is, then it is the number p which, when 10 (denoted log10) or e (when talking about the natural logarithm) is raised to that power (i.e. 10p, ep) yields n. Hence it goes up very slowly as n increases (it is the exact opposite of an exponential increase in fact):
log10(10) is 1 (101 == 10)
log10(100) is 2 (102 == 100)
log10(1000) is 3 (103 == 1000)
Apologies if you already knew all this.
in this case n^3 isnt enough
That's not true. The outer loop in Five runs exactly n times. For each value of i, the inner loop runs exactly i² times, so the number of steps the outer loop does is the sum of i² while i runs from 0 to n-1, which is n/6 - n²/2 + n³/3 (simple to prove with induction). This is a polynomial of third degree, therefore it is O(n³).
I'm afraid you're not approaching the problem correctly: blindly testing against functions will only get you so far.
The O() notation is actually like saying, for a really big value of x, the function completes in time(aO(x)), where a is an arbitrary constant (can be 0.00001 as well as 6305789932).
Let's look at the code: the inner loop is executed i2 times, whereas (outer loop) is executed n times, with i from 0 to n.
Now, the inner operation (sum++) is executed Sumi=1,ni2,
which, by wikipedian wisdom becomes (*):
Then it's time to apply the O() notation. For a big n (say 10100), n3 overwhelms n2 and even more n1, so you just discard them: O(*) = O(n3), which is the solution to the excercise.
HTH
Try to understand it like this-
We need to find the number of times the loops will execute to find the time complexity.
The sum here also represents the same number, that is why you can use it in place of time in your complexity functions. This assumption is based on the assumption that each processing of a statement takes a constant time.
If we count the number of times the loops run-
for i = 0
the inner loop runs 0 times
for i = 1
the inner loop runs 1 time
for i = 2
the inner loop runs 4 times
for i = 3
the inner loop runs 9 times
so for i = m
the inner loop runs m*m times
So the total number of statements processed can be found as --
sum = 0 + 1 + 4 + 9 + .... + mm + ... +(n-1)(n-1)
sum = 1 + 4 + 9 + .... + mm + ... +(n-1)(n-1)
These are squares of natural numbers
sum of first N natural numbers can be found as - N(N+1)(2N+1) / 6
in our case N=n-1
so sum = (n-1)(n)(2n-1) / 6
sum = (n.n -n) (2n -1) /6
sum = (2n.n.n - 2n.n - n.n -n) /6
sum = (2n^3 -3n^2 -n) / 6
sum = 1/3n^3 - 1/2n^2 -1/6n
Now, the Big O will only consider the highest order of n..
So your complexity is of the order of n^3
Now your time complexity function for n^3 will take exactly this number and divide it by n^3
so your sum would be like 1/3 - 1/2n^-1 -1/6n^-2.
and for n^4 , an even smaller number, which will get even smaller as n increases which explains gradual reduction to 0.

Categories

Resources