Reputation: 23
Having an issue compiling. The compiler is saying a variable is not used even though I use it on line 25.
Error: [line: 21] Warning: The value of the local variable pay is not used
// CreatePayroll.java takes wages and hours from file and creates pay file.
import java.util.*;
import java.io.*;
public class CreatePayroll {
public static void main(String[] args) {
try{
//Scanner for input file
File inputFile = new File("employees.txt");
Scanner fin = new Scanner(inputFile);
//Printwriter for output file
File outputFile= new File("payroll.txt");
PrintWriter fout = new PrintWriter(outputFile);
//read input file creates new file
while ( fin.hasNextLine() ) {
String firstName = fin.next();
String lastName = fin.next();
double wage = fin.nextDouble();
double hours = fin.nextDouble();
//Calculates pay
if (hours > 40) {
double pay = (wage*40)+((hours-40)*(wage*1.5));
} else {
double pay = wage*hours;
//last line to print to out file
fout.println(firstName + " " + lastName + " $" + pay);
}
}
//cleanup
fin.close();
fout.close();
System.out.print("DONE! See 'payroll.txt'.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Upvotes: 1
Views: 44
Reputation: 285450
You have a severe scope problem: you're declaring the pay variable twice inside your both the if
and else
statements, meaning that these very local variables are only visible within these blocks. Don't do that. Declare pay above the if/else block so it can be used throughout the method.
so change:
if (hours > 40) {
double pay = (wage*40)+((hours-40)*(wage*1.5));
} else {
double pay = wage*hours;
//last line to print to out file
fout.println(firstName + " " + lastName + " $" + pay);
}
to:
// declare pay prior to the if/else blocks
double pay = 0.0;
if (hours > 40) {
pay = (wage*40)+((hours-40)*(wage*1.5));
} else {
pay = wage*hours;
}
// get the line below **out** of the else block
fout.println(firstName + " " + lastName + " $" + pay);
Upvotes: 5