Search code examples
javaparentheses

Using parenthesis for calculation in Java


I wrote a program which calculates the tax you have to pay but there is something I didn't understand. It is possibly a simple thing that I don't know.

Here is my entire code:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    System.out.println("Type your income and press enter...");
    int income = in.nextInt();
    int tax, extra;

    if (income <= 10000) {
        tax = income * (15/100);
        System.out.println("The tax you have to pay is " + tax);
    } else if (income <= 25000) {
        income -= 10000;
        tax = income * (20/100) + 1500;
        System.out.println("The tax you have to pay is " + tax);
    } else if (income <= 58000) {
        income -= 25000;
        tax = income * (27/100) + 4500;
        System.out.println("The tax you have to pay is " + tax);
    } else {
        income -= 58000;
        tax = income * (35/100) + 13410;
        System.out.println("The tax you have to pay is " + tax);
    }
}

This way program doesn't calculate properly. For instance, if I write 9000, the output is 0. If I put, 3000, the output is 1500. Shortly, it omits the

income * (20/100)

part. Therefore, I just deleted parenthesis around them and did this:

tax = income * 20/100 + 1500;

and surprisingly it worked.

My question is simply why? I know parenthesis are not obligatory in this situation, however, I thought it could be easier to read when written in parenthesis. Why cannot I use them?


Solution

  • The problem is that integer division doesn't take into account fractional numbers. So 20 / 100 == 0.

    In your specific example, since * and / have same precedence and are left-associative then

     income * 20 / 100
    

    is evaluated as

    (income * 20) / 100
    

    That's why the result could seem correct (but it doesn't, since for an income <= 5 you will get 0 too.

    Just turn one of the values into a float and then cast the result back, eg:

    (int)(income * (15.0f/100))