【发布时间】:2016-01-29 01:08:35
【问题描述】:
问题: 编写一个程序来计算公司 5 名按小时计酬的员工的工资。您的程序将为 5 名员工中的每一个输入员工 ID、他们工作的小时数和他/她的工资率。这些数据将存储到 3 个并行数组中:employee_ID、hours 和 payrate。然后您的程序将调用一个方法来计算每个员工的工资,结果将存储在另一个并行数组中。并排输出 4 个并行阵列。然后,您的程序将调用 3 个方法:findAve 确定 5 名员工的平均工资,findMax 和 findMin 确定并返回分别获得最高和最低工资的员工的 ID。结果会在main方法中输出。
问题:如何实现方法调用以获取数组平均值?
代码:
public class Employees {
public static void main(String[] args) {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
int[] id;
id = new int[5];
int[] payrate;
payrate = new int[5];
int[] wage;
wage = new int[5];
final int EMPLOYEES = 5; // Number of employees
int[] hours = new int[EMPLOYEES]; // Array of hours
System.out.println("Enter the hours worked by " +
EMPLOYEES + " employees.");
// Get the hours for each employee.
for (int index = 0; index < EMPLOYEES; index++)
{
System.out.print("Employee " + (index + 1) + ": ");
hours[index] = keyboard.nextInt();
}
System.out.println("The hours you entered are:");
// Display the values entered.
for (int index = 0; index < EMPLOYEES; index++)
System.out.println(hours[index]);
System.out.println("Enter the payrate worked by " +
EMPLOYEES + " employees.");
// Get the payrate for each employee.
for (int index1 = 0; index1 < EMPLOYEES; index1++)
{
System.out.print("Employee " + (index1 + 1) + ": ");
payrate[index1] = keyboard.nextInt();
}
System.out.println("The payrate you entered are:");
// Display the values entered.
for (int index1 = 0; index1 < EMPLOYEES; index1++)
System.out.println(hours[index1]);
System.out.println("Enter the wage worked by " +
EMPLOYEES + " employees.");
// Get the wage for each employee.
for (int index2 = 0; index2 < EMPLOYEES; index2++)
{
System.out.print("Employee " + (index2 + 1) + ": ");
wage[index2] = keyboard.nextInt();
}
System.out.println("The wage you entered are:");
// Display the values entered.
for (int index2 = 0; index2 < EMPLOYEES; index2++)
System.out.println(wage[index2]);
}
//A method that calculates and returns the average of a passed array.
public static void calculateAverage (int[] wage)
{
int average = 0;
int total = 0;
for (int i=0; i<=wage.length; i++)
{
total += wage[i];
}
average = (total / wage.length);
return;
}
System.out.println(average);
}
【问题讨论】:
-
为什么有这么多信息?你能只留下必要的部分,而不把整个背景带入问题吗? (您的实际问题可以放在 4-5 行中)
-
如果您的
calculateAverage方法旨在返回平均值,则它可能不应该是void。同样i<=wage.length将抛出IndexOutOfBoundsException。应该是i<wage.length