所以这是我的作业,对我而言,它似乎是一个可变范围的问题。我已经尝试定义一个全局,但也许我做错了,因为这似乎也不满足我的编译器。我目前正在使用SublimeText2进行代码编写,但似乎没什么帮助。我应该使用Eclipse或Aptana Studio等IDE吗?
// 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 :(得分:7)
如果default
个语句都没有匹配,则需要case
个案例。
答案 1 :(得分:4)
扩展路易斯的回答: 改变
switch(employeeRating)
{
case 1: employeeBonus = (employeeSalary * BONUS_1);
break;
case 2: employeeBonus = (employeeSalary * BONUS_2);
break;
case 3: employeeBonus = (employeeSalary * BONUS_3);
break;
};
要
switch(employeeRating)
{
case 1: employeeBonus = (employeeSalary * BONUS_1);
break;
case 2: employeeBonus = (employeeSalary * BONUS_2);
break;
case 3: employeeBonus = (employeeSalary * BONUS_3);
break;
default: employeeBonus = (employeeSalary * NO_BONUS);
break;
};
我在那里保持乘法以保持计算相同,所以如果“没有奖金”的概念变成“没有个人奖励,但给予每个没有奖励的所有人0.5%”{{1} }可以设置为0.5%,它会工作。不太可能,但这只是为什么它是这样的一个例子。否则,只需将NO_BONUS
设置为0或employeeBonus
即可。由你决定。
答案 2 :(得分:1)
问题是您的第54行System.out.println("Employee Bonus $" + employeeBonus);
正在提供编译时错误 本地变量employeeBonus
可能尚未初始化
这可以通过在#18行初始化employeeBonus变量来解决:double employeeBonus = 0;
或者
在您的switch语句中添加default
个案例,如下所示:
default:
employeeBonus = 0;
答案 3 :(得分:1)
在方法(局部变量)中声明变量时,必须在使用变量之前初始化局部变量。在您的情况下,为employeeBonus提供默认值。