r/programminghelp • • 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 comments sorted by

2

u/marko312 Jul 29 '20
System.out.println("With " + TAX * 100 + "% tax,  purchase  is $" + cost + cost * TAX);

All the + are evaluated left to right for the string to print. In particular, this means that "..." + cost + cost * TAX first appends cost to the other string, then appends cost * TAX.

To prevent this, you can add parentheses ( ) around the part you want to be added arithmetically.

3

u/[deleted] Jul 29 '20

Thank you so much this makes so much sense