r/programminghelp • u/[deleted] • Jul 29 '20
Java simple code need help (Java)
in this code, If I put in 12 I am supposed to get 12.72, but get 12.00.72
any advice, not sure how to change that
import java.util.Scanner;
public class DebugTwo4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String costString;
double cost;
final double TAX = 0.06;
System.out.println("Enter price of item you are buying");
costString = input.next();
cost = Double.parseDouble(costString);
System.out.println("With " + TAX * 100 +
"% tax, purchase is $" + cost + cost * TAX);
}
}
4
Upvotes
2
u/marko312 Jul 29 '20
All the
+are evaluated left to right for the string to print. In particular, this means that"..." + cost + cost * TAXfirst appendscostto the other string, then appendscost * TAX.To prevent this, you can add parentheses
( )around the part you want to be added arithmetically.