【发布时间】:2016-03-03 23:09:01
【问题描述】:
在我的面向对象编程课程中,我有一个作业要求我开发一个 java 代码,该代码在使用 .txt 文件中的信息时打印出假公司的工资信息。我能够让它打印出员工姓名和所有内容,但我在理解如何获得平均工资时遇到了一点麻烦,我已经开始了一种方法,它在下面的代码。任何帮助将不胜感激。
员工等级:
public class Employee {
private String firstName;
private String lastName;
private String rank;
private double salary;
public Employee(String firstName, String lastName, String rank, double salary) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.rank = rank;
this.salary = salary;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
和
prog5 类:
import java.util.*;
import java.io.*;
public class Prog5 {
public static void main(String[] args) {
String firstName = null;
String lastName = null;
String rank = null;
double salary = 0.0;
Scanner inFile = null;
Employee[] arr = new Employee[99];
int num = 0;
try {
inFile = new Scanner( new File ( "c:\\Users\\admin\\workspace\\Shumaker5\\src\\employees.txt"));
}
catch(FileNotFoundException e) {
System.err.println(" File not found");
System.exit(1);
}
//read file
while(inFile.hasNext()) {
try {
firstName = inFile.next();
lastName = inFile.next();
rank = inFile.next();
salary = inFile.nextDouble();
}
catch(InputMismatchException e) {
System.err.println("File format error");
System.exit(1);
}
Employee emp = new Employee(firstName, lastName, rank, salary);
arr[num] = emp;
num++;
/**
* method to calculate average
* @param temperatures
* @param counter
* @return
*/
/** public static double average( double[] salary, int num )
{
double sum = 0;
for( int t = 0; t < num; t++)
{
sum += salary[t];
}
return (double) sum / num;
} */
System.out.println(emp);
}
System.out.println();
System.out.println("Wayne Industries");
System.out.println();
System.out.println("Number of Employees: " + num);
System.out.println("Average Salary: ");
System.out.println("Annual Total: ");
System.out.println();
System.out.printf("%-15s %-15s %-6s %-8s \n", "Last Name", "First Name", "Rank", "Salary");
System.out.println();
for(int x = 0; x < num; x++) {
System.out.printf("%-15s %-15s %-6s %-8.2f\n", arr[x].getLastName(),
arr[x].getFirstName(), arr[x].getRank(), arr[x].getSalary());
}
inFile.close();
}
}
【问题讨论】:
-
您能指出您遇到问题的地方吗?当你有一个特定的问题时,你应该避免只把你所有的代码...
-
我说问题区域被注释掉了。它在 prog 类中