英文:
Multiple "cannot be resolved or is not a field" in Java
问题
I'm working on a code for grocery shopping but the very first part I worked on got me confused. Even though I'm sure name, price, and taxable are already declared, and it works with this.xxx. For some reason obj.xxx doesn't register. Any help would be greatly appreciated, thank you!
public class GroceryItem {
private String name;
private double price;
private boolean taxable;
public boolean equals(Object obj){
return (this.name==obj.name && this.price==obj.price && this.taxable==obj.taxable); //fields after obj aren't working, ex) this.name is fine but obj.name isn't
}
public String toString() {
String taxableStr = String.valueOf(taxable);
return String.format("%s: %.2f: %s", name, price, taxableStr);
}
}
英文:
I'm working on a code for grocery shopping but the very first part I worked on got me confused. Even though I'm sure name, price, and taxable are already declared, and it works with this.xxx. For some reason obj.xxx doesn't register. Any help would be greatly appreciated, thank you!
public class GroceryItem {
private String name;
private double price;
private boolean taxable;
public boolean equals(Object obj){
return (this.name==obj.name && this.price==obj.price && this.taxable==obj.taxable); //fields after obj aren't working, ex) this.name is fine but obj.name isn't
}
public String toString() {
String taxableStr = String.valueOf(taxable);
return String.format("%s: %.2f: %s", name, price, taxableStr);
}
}
</details>
# 答案1
**得分**: 1
对象类没有您尝试获取的属性。
如果您想比较两个相同类型(类)的类,则首先需要进行转换:
```java
GroceryItem castedObj = (GroceryItem) obj;
最好在进行转换之前检查对象是否是所需类的实例(使用 instanceof
)。
英文:
Object class does not have attributes you are trying to get.
If you want to compare two classes of the same type (class), you need to cast it first:
GroceryItem castedObj = (GroceryItem) obj;
Ideally, check if the obj is instance of the required class before casting (using instanceof
)
答案2
得分: 1
public boolean equals(Object obj){
if (!(obj instanceof GroceryItem)) {
return false;
}
GroceryItem grocery = (GroceryItem) obj;
return (this.name.equals(grocery.name) && this.price == grocery.price && this.taxable == grocery.taxable);
}
英文:
The Object
class does not contain the fields name
, price
and taxable
. To compare these fields you can typecast the object to GroceryItem
class.
public boolean equals(Object obj){
if (!(obj instanceof GroceryItem)) {
return false;
}
GroceryItem grocery = (GroceryItem) obj;
return (this.name.equals(grocery.name) && this.price == grocery.price && this.taxable == grocery.taxable);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论