2015-11-13 63 views
1

編譯問題。編譯器是說即使我用它上線的變量不使用25在java中遇到變量問題

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(); 
    } 
    } 
} 
+2

閱讀有關變量的作用域。 – Tunaki

+0

您在'if'塊中的'pay'聲明在'else'塊中不可見。 –

+0

請不要用_ [FIXED] _標記您的問題,而應接受幫助您解決問題的最佳答案。如果沒有任何現有答案有幫助,請發佈您自己的解決方案作爲答案並接受。 –

回答

5

你有一個嚴重的問題的範圍:你聲明的薪酬變量兩次內的兩個ifelse語句,這意味着這些非常局部變量僅在這些塊中可見。不要這樣做。在if/else塊之上聲明支付,以便可以在整個方法中使用。

所以更改:

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); 
+0

糟糕,已更正的錯誤 –

+0

那麼它會如何與其他人交互以正確計算應得的工資? – Sean

+0

@Sean:我以爲我在上面的代碼中展示過。 –