如何创建一个布尔型的 equals 方法来比较数组中的对象。

huangapple go评论70阅读模式
英文:

How do I create an boolean equals method compares objects in an array

问题

以下是你的代码翻译部分:

雇员类:

public abstract class Employee
{

private String lastName;
private String firstName;
private String ID;


public abstract void increasePay(double percentage);
public abstract void decreasePay(double percentage);
public abstract double getMonthlyPay();

public Employee(String last, String first, String ID)
   {
   lastName = last;
   firstName = first;
   this.ID = ID;
   } 

public void setLast(String last)
   {
      lastName = last;
   }
   
public void setFirst(String first)
   {
      firstName = first;
   }
   
public void setIdNumber(String ID)
   {
      this.ID = ID;
   }


public String getLastName()
{
   return lastName;
}

public String getFirstName()
{
   return firstName;
}

public String getName()
{
   return firstName + lastName;
}

public String getIdNumber()
{
   return ID;
}
}

小时工类

```java
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;

public HourlyWorker(String last, String first, String ID, double rate)
{
   super(last, first, ID);
   hourlyRate = rate;
}

public void setHours(int hours)
{
   this.hours = hours;
}

public int getHours()
{
   return hours;
}

public void setHourlyRate(double rate)
{
   if ( hours > 160 )
       this.hourlyRate = hourlyRate * 1.5;
    else 
       this.hourlyRate = rate;
}

public double getHourlyRate()
{
   return hourlyRate;
}


public void setMonthlyPay(double monthlyPay)
{
   monthlyPay = hourlyRate * hours;
}

public double getMonthlyPay()
{
   return hourlyRate * hours;
}

public void increasePay(double percentage)
{
   monthlyPay = monthlyPay * (1 + percentage / 100);
}

public void decreasePay(double percentage)
{
   monthlyPay = monthlyPay * (1 - percentage / 100);
}

public String toString() 
   {
        String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
                         + getIdNumber() + " \nHourly Rate: " + hourlyRate;
        return result;
   }

}

测试类(目前正在测试增加工资部分)

public class TestEmployee2
{
   public static void main(String[] args)
   {
   Employee [] staff = new Employee[3];
      Supervisor sup = new Supervisor("Boss", "Jim", "JB7865", 54000);
      HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 11.95);

      hw1.setHours(200);
            
      staff[0] = sup;
      staff[1] = hw1;        
        
   System.out.println(staff[0].getMonthlyPay());
   staff[0].increasePay(5);
   System.out.println(staff[0].getMonthlyPay());

   System.out.println(staff[1].getMonthlyPay());
   staff[1].increasePay(10);
   System.out.println(staff[1].getMonthlyPay());
   
}
}

主管类:

public class Supervisor extends Employee
{
private double annualSalary;
private double monthlyPay;

public Supervisor(String last, String first, String ID, double salary)
{
   super(last, first, ID);
   annualSalary = salary;
}

public void setAnnualSalary(double salary)
{
   annualSalary = salary;
}

public double getAnnualSalary()
{
   return annualSalary;
}

public double getMonthlyPay()
{
   return ((annualSalary + (annualSalary * .02)) / 12);
}

public void increasePay(double percentage)
{
   monthlyPay = monthlyPay * (1 + percentage / 100);
}

public void decreasePay(double percentage)
{
   monthlyPay = monthlyPay * (1 - percentage / 100);
}

public String toString() 
   {
        String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
                         + getIdNumber() + "\nAnnual Salary: " + annualSalary;
         return result;
   }
}

输出是:

4590.0 4819.5 2390.0 2629.0

看起来似乎没有修改 getMonthlyPay()

应该是:

4590.00 4819.50 2390.00 2629.00

英文:

My programming assignment tasked me with writing an increase/decreasePay abstract method that must be put in my abstract employee class. I can't seem to get the the method correct in HourlyWorker so that it will take increase or decrease the pay by a "percentage". My math is sound (monthly pay - or + (monthly pay * the percentage), but my output in my test class is coming out the same after increasing/decreasing pay. Any help?

Employee class:

abstract public class Employee
{
private String lastName;
private String firstName;
private String ID;
public abstract void increasePay(double percentage);
public abstract void decreasePay(double percentage);
public abstract double getMonthlyPay();
public Employee(String last, String first, String ID)
{
lastName = last;
firstName = first;
this.ID = ID;
} 
public void setLast(String last)
{
lastName = last;
}
public void setFirst(String first)
{
firstName = first;
}
public void setIdNumber(String ID)
{
this.ID = ID;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getName()
{
return firstName + lastName;
}
public String getIdNumber()
{
return ID;
}
}
HourlyWorkerClass
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
if ( hours > 160 )
this.hourlyRate = hourlyRate * 1.5;
else 
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public void setMonthlyPay(double monthlyPay)
{
monthlyPay = hourlyRate * hours;
}
public double getMonthlyPay()
{
return hourlyRate * hours;
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString() 
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + " \nHourly Rate: " + hourlyRate;
return result;
}
}

Testing class (currently testing increase

public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
Supervisor sup = new Supervisor("Boss", "Jim", "JB7865", 54000);
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 11.95);
hw1.setHours(200);
staff[0] = sup;
staff[1] = hw1;        
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(5);
System.out.println(staff[0].getMonthlyPay());
System.out.println(staff[1].getMonthlyPay());
staff[1].increasePay(10);
System.out.println(staff[1].getMonthlyPay());
}
}
Supervisor class:
public class Supervisor extends Employee
{
private double annualSalary;
private double monthlyPay;
public Supervisor(String last, String first, String ID, double salary)
{
super(last, first, ID);
annualSalary = salary;
}
public void setAnnualSalary(double salary)
{
annualSalary = salary;
}
public double getAnnualSalary()
{
return annualSalary;
}
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString() 
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + "\nAnnual Salary: " + annualSalary;
return result;
}
}

Output is:

4590.0 4590.0 2390.0 2390.0

Doesn't appear to be modifying getMonthlyPay()

Should be:

4590.00 4819.50 2390.00 2629.00

答案1

得分: 0

当您执行list.indexOf(temp)时,目前的操作是查找与传递给它的参数相等的Stock — 因此,它会查找价格为零的Stock,而不关心符号。这是当前代码的功能。

老实说,对于这个问题,使用indexOfequals并不是很合适。indexOf只有在您有某个与您要查找的目标完全相等的东西时才真正有用。

做类似这样的事情的最佳方法是

Optional<Stock> foundStock = list.stream().filter(stock -> stock.getName().equals(symbol)).findAny();
if (foundStock.isPresent()) {
  // 对 foundStock.get() 做一些操作
} else {
  // 没有找到股票
}
英文:

When you do list.indexOf(temp), what that does, right now, is look for a Stock that is equals to the argument passed to it -- so it looks for a Stock with price zero, not caring about the symbol at all. That's what the code does right now.

Honestly, using indexOf and equals is not really appropriate for this problem. indexOf is really only useful when you have something that's totally equal to the target you're looking for.

The best way to do something like this is

Optional&lt;Stock&gt; foundStock = list.stream().filter(stock -&gt; stock.getName().equals(symbol)).findAny();
if (foundStock.isPresent()) {
// do something with foundStock.get()
} else {
// no found stock
}

答案2

得分: 0

indexOf()是一个方法,返回列表中第一个出现的指定元素的索引。如果列表不包含此元素,则返回值为-1。
更正式地说,返回最低的索引i,满足以下条件:

if(o==null? get(i)==null :o.equals(get(i))){
    return i;
}
return -1;

如果没有这样的索引,则返回-1。

而且,您已经重写了equals方法,我猜您只想关注于相同价格的股票?:

@Override
public boolean equals(Object obj){
    if (obj instanceof Stock){   
        Stock other = (Stock) obj;
        return getPrice() == other.getPrice();
   }
   return false;
}  

根据我的观点,您已经使用了List<Stock> list,因此列表中的对象都是Stock。也许可以简化为:

@Override
public boolean equals(Object obj){
    Stock other = (Stock) obj;
    return getPrice() == other.getPrice();
}
英文:

indexOf() is a method return the index of the first occurrence of the specified element in the returned list. If the list does not contain this element, value -1 is returned.
More formally, return the lowest index i that meets the following conditions:

if(o==null? get(i)==null :o.equals(get(i))){
    return i;
}
return -1;

If there is no such index, return -1.

And you have override the equals method, I guess you just want to focus on the same price Stock?:

@Override
public boolean equals(Object obj){
    if (obj instanceof Stock){   
        Stock other = (Stock) obj;
        return getPrice() == other.getPrice();
   }
   return false;
}  

As my opinion, you have use List&lt;Stock&gt; list so the Object in the list is all Stock. Maybe it could be simplifed:

@Override
public boolean equals(Object obj){
    Stock other = (Stock) obj;
    return getPrice() == other.getPrice();
}

答案3

得分: 0

一般情况下,在实现 equals() 方法时,您会比较实体中那些值不会随时间变化的“关键”字段,而不会比较那些随时会改变值的“状态”字段。

您正在比较 sharePrice,但我认为您应该比较的是 symbol

英文:

Generally, when implementing equals(), you compare “key” fields whose values don’t change for the entity, and don’t compare “state” fields whose values change from time to time.

You are comparing sharePrice, when I believe you should be comparing symbol.

huangapple
  • 本文由 发表于 2020年10月3日 13:03:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64180916.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定