所以這是我的家庭作業,對我來說這似乎是一個變量範圍的問題。我試圖定義一個全局的,但也許我做錯了,因爲這似乎不滿足我的編譯器。我目前使用SublimeText2編寫代碼,但似乎沒有多大幫助。我應該使用Eclipse,Aptana Studio等IDE嗎?使用switch語句後變量不可用?
// EmployeeBonus2.java - This program calculates an employee's yearly bonus.
import javax.swing.*;
public class EmployeeBonus2
{
public class Globals {
public double employeeBonus;
}
public static void main(String args[])
{
// Declare and initialize variables.
String employeeName;
String salaryString;
double employeeSalary;
String ratingString;
int employeeRating;
double employeeBonus;
final double BONUS_1 = .15;
final double BONUS_2 = .10;
final double BONUS_3 = .06;
final double NO_BONUS = 0.00;
final int RATING_1 = 1;
final int RATING_2 = 2;
final int RATING_3 = 3;
// This is the work done in the housekeeping() method
// Get user input.
employeeName = JOptionPane.showInputDialog("Enter employee's name: ");
salaryString = JOptionPane.showInputDialog("Enter employee's yearly salary: ");
ratingString = JOptionPane.showInputDialog("Enter employee's performance rating: ");
// Convert Strings to int or double.
employeeSalary = Double.parseDouble(salaryString);
employeeRating = Integer.parseInt(ratingString);
switch(employeeRating)
{
case 1: employeeBonus = (employeeSalary * BONUS_1);
break;
case 2: employeeBonus = (employeeSalary * BONUS_2);
break;
case 3: employeeBonus = (employeeSalary * BONUS_3);
break;
};
// This is the work done in the endOfJob() method
// Output.
System.out.println("Employee Name " + employeeName);
System.out.println("Employee Salary $" + employeeSalary);
System.out.println("Employee Rating " + employeeRating);
System.out.println("Employee Bonus $" + employeeBonus);
System.exit(0);
}
}
嘗試編譯時出現此錯誤。
EmployeeBonus2.java:54: variable employeeBonus might not have been initialized
System.out.println("Employee Bonus $" + employeeBonus);
錯誤表示該變量未初始化。在聲明期間,它始終是一個很好的練習,用一些值初始化變量(可能爲0)。 – Jayy 2012-03-06 09:48:22
@KaipaMSarma指定一個初始值將隱藏錯誤,隱藏每次執行基本上只有一個賦值並且是一個壞主意的事實。 – 2012-03-06 10:04:08