elibretto - 1 year ago 70
Java Question

# Carry a double variable over from one method to another

I have a program to calculate tax payable on an income. The first method taxPayable() calculates the amount of tax that would be paid on this income and the second one incomeRemaining() should calculate the income remaining after the tax has been deducted but the variable tax is changing back to its first assignment of 0. How can i change my code so that it carries over to the next method?

``````public class TaxCalculator {
static double tax = 0;
public static void taxPayable(int income) {
if (0 <= income && income <= 100) {
double tax = 0;
System.out.print("Tax payable on this income is equal to " + tax);
}
else if (101 <= income && income <= 150) {
double tax = 0 + (income-100)*0.1;
System.out.print("Tax payable on this income is equal to " + tax);
}
else if (151 <= income && income <= 200) {
double tax = 0 + 50*0.1 + (income-150)*0.2;
System.out.print("Tax payable on this income is equal to " + tax);
}
else if (201 <= income && income <= 300) {
double tax = 0 + 50*0.1 + 50*0.2 + (income-200)*0.4;
System.out.print("Tax payable on this income is equal to " + tax);
}
else if (301 <= income && income <= 400) {
double tax = 0 + 50*0.1 + 50*0.2 + 100*0.4 + (income-300)*0.6;
System.out.print("Tax payable on this income is equal to " + tax);
}
else {
double tax = 0 + 50*0.1 + 50*0.2 + 100*0.4 + 100*0.6 + (income-400)*1.2;
System.out.print("Tax payable on this income is equal to " + tax);
}
}
public static void incomeRemaining(int income) {
TaxCalculator.taxPayable(income);
double \$\$ = income - tax;
System.out.println("\nIncome remaining after tax is equal to " + \$\$);
}
public static void main(String[] args) {
TaxCalculator.incomeRemaining(400);
}
``````

}

Thus: simply remove all those

``````double tax = 0;
``````

statements from the body of your method!

But: the better approach would be that your method returns that value. There is not much sense in using global variables to "communicate" values; when your method could simply return them! So change the method from "void" to "double", and simply return the computed value!

Plus: you duplicated those print statements for no reason. Just do one print in the end of the method! Seriously: whenever you have two pieces of code that do exactly the same thing ... get rid of the second one somehow!

And finally: never ever use special chars such as \$ for variable/method/... names in your code!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download