编译问题。编译器说即使我在第25行使用它也不使用变量。
错误: [行:21] 警告:未使用本地变量pay的值
// 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();
}
}
}
答案 0 :(得分:5)
您有严重的范围问题:您在if
和else
语句中声明了薪酬变量两次,这意味着这些非常局部的变量只是在这些街区内可见。不要那样做。在if / else块之上声明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);
}
为:
// 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);