Why is it adding the variables wrong? - java

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.

Related

Char of string outputting incorrectly

This is my program and what I am trying to achieve is taking the char value in string amount1 at position 1 i.e for example amount1=$3.00 amount2=2. However it doesn't print out what I expected, 2.
System.out.print("$"+cost[0]+".00 remains to be paid. Enter coin or note: ");
String amount1 = keyboard.nextLine();
char amount2 = amount1.charAt(1);
String amountcheck = "$"+cost[0]+".00";
int [] remainder = new int[1];
if (amount1.equals(amountcheck)) {
System.out.println("Perfect! No change given."); }
if (amount2 < cost[0]) {
remainder[0] = cost[0] - amount2; }
System.out.println("Remainder = "+remainder[0]);
System.out.println(+amount2);
For example,
$3.00 remains to be paid. Enter coin or note: $2.00
Remainder = 0
50
The problem is both in lines 2 and 3. Firstly 3, It don't understand why it outputs 50 as char at amount1 index 1. If i'm not wrong don't char positions work similarly off array index systems. Secondly line 3, the if statement in lines of 8 and 9 of my original code don't seem to catch that amount 2 < cost[0] and don't do the following operations.
So what I expected to happen when I am taking char at position 1 of "$2.00" is newamount would be equal to 2 instead of 50 which the program is outputting.
I've tried changing the char positions but all this seems to do is decrement the value.
You set your amount2 as a char and when you print it, it translates to the ASCII number of that charater which for the charater '2' is 50.
If you want to output 2 you should change your amount2 to type intand parse the char to integer like this Integer.parseInt(""+amount1.charAt(1)); in line 3.
You are using a char to store a numeric value, but that value is a character, not a number. Meaning you are storing '2' which is actually 50 in ASCII. You should remove the value of 48 to get the correct value ('0') or parse the String into a number directly with Integer.parseInt(String).
But as I said in comment, this is easy to correct so I will not provide much more code to this.
But let's be honnest, your logic is risky from the beginning.
You are asking the user to input an amount in a specific format : "$#.00". If the number is two digit $##.00 it fails, if he add a space or don't put the $ or any mistake that users are professional to find, it fails.
First, you should simplified this, do you need the $ ? Ask for dollar currency if you want to specifiy it.
Then, do you need decimals ? Let first assume you don't (see Note for decimal hint).
You just need to input an integer value through the Scanner, which provide method to get Integer -> Scanner.nextInt()
int ammountReceived = keyboard.nextInt();
Then you need to see if this is
Equals
Too much
Not enough
Like this :
int remainder = amountToPay - amountReceived;
if(remainder == 0){
//equals
} else if(remainder > 0){
//not enough
} else {
//too much
}
This would give a simpler solution of :
Scanner sc = new Scanner(System.in);
System.out.print("Amount to pay : $");
int amountToPay = sc.nextInt();
System.out.print("Amount received : $");
int amountReceived = sc.nextInt();
int remainder = amountToPay - amountReceived;
if (remainder == 0) {
System.out.println("That perfect, thanks.");
} else if (remainder > 0) {
System.out.println("Remaining : $" + remainder);
} else {
System.out.println("Need to give back : $" + -remainder);
}
sc.close();
Yours and mine are close, but you will see this is more readable and focused on the problem, I don't play with char to get from a specific String pattern, I am focused on the problem -> to get paid ;)
Now, you have to add a loop here to ask again until you received the correct amount. But please, don't read a numerical String character by character...
Note :
Scanner.nextInt throws exception if the format is incorrect (not an integer)
You can easily adapt this to get double, float or better BigDecimal

Calculate additional value in Java

I need to write a java method to calculate an additional value.
I have a candy bar that costs $10 (price). I need to calculate an added value of 20% (ADDED_VALUE) so I do the following:
price + price*ADDED_VALUE or 10 + 10*20%
and I get 12. But now I need to calculate 10% (NEW_ADD_VALUE) on this 12, but I don't know how to do it.
What I've tried so far:
double priceWithAddedValue() {
return price + price * ADDED_VALUE + price * NEW_ADDED_VALUE
}
However the above code returns 13 and I'm suppose to get 13.2.
I think you should refactor this into a general method which takes an initial double and a fraction indicating what should be added:
double addFraction(double initialValue, double fraction) {
return initialValue + fraction*initialValue;
}
After this, it is very easy to do this twice:
addFraction(addFraction(10, 0.2), 0.1);
You could of course split this into multiple statements.
So this would look like this in your example:
double priceWithAddedValue(){
return addFraction(addFraction(price, ADDED_VALUE), NEW_ADDED_VALUE);
}
Hope this helps!
The most important thing you need to focus on is order of operations, especially the function of the parenthesis, since not only is it valuable knowledge to posses for programming but also for day to day life. (if you use math in your day to day life)
What your trying to do is multiply a number, by the addition of, the product of two numbers.
double priceWithAddedValue() {
return (price + price * ADDED_VALUE) * NEW_ADDED_VALUE;
}
Next you should focus on variable types, like float, int, double, char. The problem you're facing with getting 3 instead of 3.2 is due to int only representing integers (. , -2, -1, 0 , 1 , 2 , .). be fine using a double

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

Java: print double - println or printf

Suppose I have the following code:
double median = med(10.0, 12.0, 3.0); //method returns middle number as double
Now, I want to write a message stating the median. Can this be done using println(), like the following:
System.out.println("Your number was " + median);
Or must I use printf() with double values?
The reason I ask is because I have seen both practices online 1, but when I try using println() I get an error, unless i write:
System.out.println(median);
Hence, can you use println() to print out double values and strings, or must you use printf() for that purpose?
The printf method can be particularly useful when displaying multiple variables in one line which would be tedious using string concatenation:
The println() which can be confusing at times. (Although both can be used in almost all cases).
double a = 10;
double b = 20;
System.out.println("a: " + a + " b: " + b);// Tedious string concatenation.
System.out.printf("a: %f b: %f\n", a, b);// Output using string formatting.
Output:
a: 10.0 b: 20.0
a: 10,000000 b: 20,000000
You can do both (if System.out.println("Your number was " + median); is not working you have something else wrong. Show us the stack trace). printf allows you some more formatting options (such as the number of decimal places) without having to use a DecimalFormat, but it is a choice on style rather than anything else.
Personally I find string concatenation easer on the eyes and easer to maintain. The %blah gets lost in the string, errors in string concatenation is a compile time error and adding a new variable requires less thought. However I'm in the minority on this.
The pros in printf is that you don't need to construct a bunch of formatters, others find its format easer on the eyes and when using a printf like method provided by a logging framework the string building only happens if actually required.
double value = 0.5;
System.out.println("value: " + value);
System.out.printf("value: %f", value);
If you want to set a number of decimal places:
double value = 0.5;
// String concatenation
DecimalFormat df = new DecimalFormat("0.000");
System.out.println("value: " + df.format(value));
// printf
System.out.printf("value: %.3f", value);

Java Modulus Weird

I write code to test methods, display food and price:
import java.util.Scanner;
public class JavaTutorial5Class {
public static void main(String[] args)
{
greeting("Thunderdome");
prices("Fatburger", 7.50);
}
static void greeting(String restaurant)
{
System.out.println("Welcome to " + restaurant);
}
static void prices(String burger, double price){
System.out.print(burger + " is " + "$" + price);
//System.out.println(Math.ceil(price % 10));
if (Math.ceil(price % 10) == 8.0){
System.out.print("0");
}
}
}
Why is price % 10 == 8.0? And is this really what you have to do to get the tailing 0 on there?
EDIT: All this code is supposed to do is print "Fatburger is $7.50" the problem is that simply giving it the argument 7.50 converts it to 7.5.
In this code, the reason you are getting 8.0 is due to you using Math.ceil.
7.5 % 10 is 7.5, and Math.ceil(7.5) is 8.0.
However, and this is something that comes up extremely often and is a very common mistake for beginners... prices should almost never be stored as doubles. Double arithmetic is not always as precise as you would expect, mainly because of how doubles are actually stored. For example, consider this:
double sum = 0.0;
int n = 6;
for (int i = 0; i < n; i++) {
sum += 1.0 / n;
}
System.out.println(sum);
You would expect it to output 1.0, but it actually outputs 0.9999999999999999
The correct way to handle prices is with two ints: one for dollars, one for cents.
Try this instead:
static void prices(String burger, double price){
System.out.print(burger + " is $" + price);
if ((int)(price * 10) == price * 10)
System.out.print(0);
}
As you have it now, 7.5 % 10 simply returns 7.5 and the Math.ceil rounds this up to 8.0.
price % 10 is actually 7.5. Modulu is the remainder of division (or how many times a number can fit into another). For example, 22 % 10 is 2, since 10 can fit into 22 twice without going over. Taking the ceiling, which raises it to the nearest integer, raising 7.5 it to 8. Hence the if statement is resulting as true.
I think ultimately the solution he wants (to print a double in the form of currency) can be solved as so...
Add import
import java.text.NumberFormat;
and use this code
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.print(burger + " is " + "$" + nf.format(price));
Forget all the modulo stuff (it is over complicating and incorrect way to achieve what you are asking for).
Also there is a slight rounding issue with doubles and if you need perfect precision (doubtful given the rest of your code), but typically the standard is to use 2 ints to store currency).
Use the following command to format your string correctly:
System.out.printf(%s is $%.2f, burger, price)
Reference this page for a tutorial on string formatting: http://www.homeandlearn.co.uk/java/java_formatted_strings.html
The %s will be replaced by the value of burger, formatted as a string.
The %.2f will be replaced by the value of price, formatted as a decimal number with exactly 2 places after the decimal point.

Categories

Resources