Home > Net >  How do I add the tax inside the if statement when I chose one variable already?
How do I add the tax inside the if statement when I chose one variable already?

Time:07-11

I am trying to create a tax calculator in Java, but I just can't seem to figure out how to tax the income when I have already used the if statement to verify the province so I can do the calculations.

How do I do the calculations without using a else if statement within the if statement?

(I just started Java and suck. So sorry for all the mistakes)

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {

    Scanner income = new Scanner(System.in);
    System.out.println("What is your taxable income: ");
    double taxable_income = income.nextDouble();
    System.out.println("You're income is: "   taxable_income);

    Scanner province = new Scanner(System.in);
    System.out.println("In which province do you live? (1 for BC, 2 for Alberta, and 3 for Ontario):  ");
    int province_inhabiting = province.nextInt();
    System.out.println("You chose "   province_inhabiting);

    if (province_inhabiting == 1) {
      taxable_income <= 40707 {
        tax = income & 0.0506;
      }
      
      (taxable_income >= 40707 && taxable_income <= 81416) {
        tax = income & 0.077;
      }

       (taxable_income >= 81416 && taxable_income <= 93476) {
        tax = income & 0.105;
      }

      (taxable_income >= 93476 && taxable_income <= 113503) {
        tax = income & 0.105;
      }
      
      }
    }
  }
}

The problem I'm having here is that I want to do the calculation within the if statement, the problem is I just don't know how to do it within the if statement. Basically let's say province is a variable which has 3 parts to it (BC, Ontario, and Alberta) now within this if statement I want to take the inputted income (the user inputs earlier) and tax it by let's say 5.6% or * 0.056. How would I do that under an if statement in Java.

CodePudding user response:

For almost all the times, you can replace if else if else statement to using a Map object, and this is a better practice in a lot ways. You should checkou principle in Software Design Pattern, like this one open-close principle. You can add a lot of key:values to the map, and your code is not modified, but added.

if (a == 1){
   print(1)
} else if (a >1 && a < 100){
   print(10)
} else {
   print(100)
}

//change the code to 
HashMap<@Nullable Predicate<Integer>, @Nullable Consumer<Integer>> map = Maps.newHashMap();
map.put(x -> x == 1, (x) -> {
    System.out.println(1);
});
map.put(x -> x > 1 && x < 10, (x) -> {
    System.out.println(10);
});
map.put(x -> x != 1 && !(x > 1 && x < 10), (x) -> {
    System.out.println(100);
});

int a = 1;
for (Map.Entry<Predicate<Integer>, Consumer<Integer>> entry : map.entrySet()) {
    if (entry.getKey().test(a)) {
        entry.getValue().accept(a);
    }
}

  • Related