I am writing a program for computing income tax that increases the tax amount based on your personal income. I keep getting the error “variable tax might not have been initialized” on the line “return tax;” but I’m not sure why. Here is my code so far:
import java.util.Scanner; //Needed for the Scanner Class
/**
* Write a description of class IncomeTax here.
* @author
* 11/30/2012
* The IncomeTax class determines how much tax you owe based on taxable income.
*/
/**
* The getTax returns the tax for the income.
*/
public double getTax() {
double tax;
if (income <10000.0) {
tax = 0.10;
}
else {
if (income > 10001.0 && income < 30000.0) {
tax = 0.15;
}
else {
if (income > 30001.0 && income < 60000.0) {
tax = 0.25;
}
else {
if (income > 60001.0 && income < 130000.0) {
tax = 0.28;
}
else {
if (income > 130001.0 && income < 250000.0) {
tax = 0.33;
}
else {
if (income > 250001.0) {
tax = 0.35;
}
}
}
}
}
}
return tax;
}
/**
* The constructor accepts an argument for the income field.
*/
public IncomeTax(int i)
{
income = i;
}
/**
* The setIncome method accepts an argument for the income field.
*/
public void SetIncome(int i) {
income = i;
}
/**
* The getIncome method returns the income field.
*/
public int getIncome() {
return income;
}
I’m not finished yet, I still have to write the code for the user to actually input their information to compute, but I don’t want to go any further without fixing the return tax line first.
Short answer
Because you might not pass any of the
ifconditions, you aren’t guaranteed to settax. Use:Long answer
You have a lot of redundant code. You can remove a lot of it by doing this:
This way you don’t need to check things that can’t be true, and by using
else ifthe code doesn’t get indented every time. Cheers! Also, by passing an argument and making the functionstatic, you allow yourself to make the function usable in other places, if you ever need to.