int变量被连接而不是在System.out.println()中添加

dha*_*shi 7 java string

为什么total_amount并且tax_amount在下面的println语句中将它们连接在一起而不是作为数字加在一起?

public class Test{

  int total_amount,tax_amount;
  public void cal(int total_amount,int tax_amount)
 {
     System.out.println("Total amount : "+total_amount+tax_amount);
 }
  public static void main(String[] args) {
  new Test().cal(100, 20);
  }

}

Output Total amount : 10020
Expected Total amount : 120
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 16

这是因为运营商的优先权.基本上,您的代码相当于:

System.out.println(("Total amount : " + total_amount) + tax_amount);
Run Code Online (Sandbox Code Playgroud)

所以,当它total_amount是100,并且tax_amount是20时,最终会:

System.out.println(("Total amount : " + 100) + 20);
Run Code Online (Sandbox Code Playgroud)

评估为:

System.out.println("Total amount : 100" + 20);
Run Code Online (Sandbox Code Playgroud)

评估为:

System.out.println("Total amount : 10020");
Run Code Online (Sandbox Code Playgroud)

选项:

作为附注,我建议:

  • 遵循Java命名约定,使用camelCase代替underscores_separating_words,taxAmount而不是使用tax_amount
  • 更仔细地命名变量 - 调用变量是奇怪的,total_amount然后用标签打印不同的东西Total amount
  • 在这里使用静态方法,因为您实际上并未使用对象中的字段.(这些字段令人困惑,因为你没有使用它们.)

使用代码格式,您最终会得到:

public class Test {
    public static void main(String[] args) {
        calculateTotal(100, 20);
    }

    private static void calculateTotal(int preTaxTotal, int tax) {
        int totalIncludingTax = preTaxTotal + tax;
        System.out.println("Total amount: " + totalIncludingTax);
    }
}
Run Code Online (Sandbox Code Playgroud)

(你还应该考虑你要为非整数价格做什么......我建议使用整数,但要使用美分/便士/任何数字,或BigDeciml用来表示价格.)