Java 为什么添加变量是错误的?

Java 为什么添加变量是错误的?,java,decimal,Java,Decimal,我使用的是Java,但它没有正确地添加数量。我将给出我的部分代码 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",(in

我使用的是Java,但它没有正确地添加数量。我将给出我的部分代码

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+"");
final double taxrate=.08;
Map Priceproduct=new HashMap();
价格产品。价格(鞋类)(整数)50.00);
价格产品。卖出(“衬衫”(国际)30.00);
价格产品.看跌期权(“空头”(int)75.00);
价格产品。卖出价(大写)(整数)15.00);
产品价格(单位:100.00);
系统输出打印(“\n输入产品:”);
String product=keyboard.nextLine();
系统输出打印(“\n输入产品数量”);
int数量=键盘.nextInt();
int成本=价格产品。获取(产品)*数量;
整税=(整税)(成本*税率);
系统输出打印(“\n tax=“+成本*税率+”);
int TotalBill=成本+税费;
System.out.print(“\nTotal=“+cost+++tax+”);
当它加上成本和税收(这两个是正确的)时,它得到了完全错误的答案。 例如,3件衬衫=90,税等于7.2,总数变成907

是否需要使用DecimalFormat或其他格式?

更改此选项:

System.out.print("\nTotal="+cost+ + +tax+"");
为此:

System.out.println();
System.out.print("Total=" + (cost + tax));

(问题是,
+
是左关联的,因此在加法中没有括号,
“a”+b+c
表示
(“a”+b)+c
,它在两个阶段都进行字符串连接。)

当您在字符串旁边执行操作时,Java将执行该操作,就像操作数是字符串一样

在您的
System.out.println()调用中,您不需要重做计算,只需打印出变量“tax”和“totalBill”。(这将解决打印“907”的问题)


您将只获得整数值,因为您对所有内容都使用
int
type。如果您想用小数表示美分,则应使用类型
double

您正在合并这些数字,而不是添加它们。看看操作符的优先级,随时可以使用括号来打印TotalBill。他还需要将tax存储为double,而不是int。