Ike Ike - 3 months ago 9
Java Question

Variable not initialized even though I initialized it

I'm new to java and was making a program that would determine if an employee is a part timer or a regular or employee based on their employee ID, R is for regulars and P is for part timers (i.e. R-0001, P-0001). The problem I'm having is that when I print out the gross, wDay, tax, and net varibales the Eclipse says "the local variable may not have been initialized" when they were ok in the computation section of the code. What is wrong with my code?

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int sss = 100, pagibig = 100, phealth = 100, day = 15, wDay, absent;
double gross, tax, net, rRate = 500, pRate = 450;
String id;
char type;

System.out.print("Enter employee number: ");
id = scan.nextLine();
type = scan.next().charAt(0);
System.out.print("Enter number of days absent: ");
absent = scan.nextInt();
scan.close();
{
if(type == 'r' || type == 'R'){
wDay = day - absent;
gross = rRate * wDay;
tax = gross * 0.05;
net = gross - (sss + pagibig + phealth + tax);
}
else if (type == 'p' || type == 'P'){
wDay = day - absent;
gross = pRate * wDay;
tax = gross * 0.05;
net = gross - tax;
}
else{
System.out.println("Wrong employee number");
}
}
System.out.println("Employee number: " + id);
{
if(type == 'r' || type == 'R'){
System.out.println("Employee type: Regular");
}
else{
System.out.println("Employee type: Part-timer");
}
}
System.out.println("Gross income: P" + gross);
System.out.println("Number of days worked: " + wDay);
System.out.println("Number of days absent: " + absent);
{
if(type == 'r' || type == 'R'){
System.out.println("Deductions");
System.out.println("SSS: P100");
System.out.println("PagIBIG: P100");
System.out.println("PhilHealth: 100");
System.out.println("Tax: " + tax);
}
else{
System.out.println("Deductions");
System.out.println("Tax: " + tax);
}
}
System.out.println("Net income: " + net);
}

Answer

You only initialize them if type is r, R, p, or P. If it's none of those then you enter the Wrong employee number block and don't set them to anything.

All paths through your code must set them to something before they're used, otherwise Java will complain. There are a couple of ways forward: (1) set them to something in the else block; (2) add a return; statement to the else block to quit out of the program, avoiding the print statements; (3) wrap the input portion in a loop, and keep looping until the user's entered P or R.

Comments