【发布时间】:2015-04-16 04:33:20
【问题描述】:
我在介绍课程中有一个关于实施的问题。我想出了一个答案,但编译显示“编译错误(第 3 行,第 9 列):可能的精度损失”我对这种精度损失是什么感到困惑。
我的作业问题如下:
回想一下,Person 类实现了 Comparable 接口:
public class Person implements Comparable
现在假设我们要按薪水比较员工。由于 Employee 扩展了 Person,Employee 已经通过 Person compareTo 方法实现了 Comparable,该方法按年龄比较 Person 对象。现在我们要重写 Employee 类中的 compareTo 方法,以便进行工资比较。
对于这个分配,通过为该类实现一个新的 compareTo 方法来修改 Employee 类。在下面提供的空白处输入适当的代码,以便如果员工 A 的工资低于员工 B 的工资,则认为员工 A 低于员工 B。此外,如果员工 A 的工资等于员工 B 的工资,那么它们应该相等。请记住,您输入的代码位于 Employee 类中。
/**
* Compares this object with the specified object for order.
* @param o the Object to be compared.
*/
public int compareTo(Object obj)
{
这是我的代码
double b= ((Employee)obj).getSalary();
double a= this.salary;
return(a-b);
}
这是Employee类的代码:
class Employee extends Person
{
private double salary;
/**
* constructor with five args.
* @param n the name
* @param ag the age
* @param ht the height
* @param p the phone number
* @param the salary
*/
public Employee(String n, int ag, int ht, String p, double s)
{
super( n, ag, ht, p );
salary = s;
}
/**
* Get the salary.
* @return double the salary.
*/
public double getSalary( )
{
return salary;
}
/**
* Raise the employee's salary by a given percent.
* @param percentRaise
*/
public void raise(double percentRaise)
{
salary *= ( 1 + percentRaise );
}
/**
* Compares this object with the specified object for order.
* @param o the Object to be compared.
*/
public int compareTo(Object obj)
{
/* your code goes here */
}
/**
* get a String representation of the employee's data.
* @return String the representation of the data.
*/
public String toString( )
{
return super.toString( ) + " $" + getSalary( );
}
}
非常感谢任何帮助我正确回答的问题。我一直在研究这个奇异的问题一个多小时,而那个编译错误让我无所适从。谢谢!
【问题讨论】:
标签: java implementation