我遇到一个问题,方法不能被其他类看到,我无法弄明白。 我有一个Shopping_Basket类,它有一个商品列表(商品是一个类)。我试图让Shopping_basket类中的Merchandise列表到达Merchandise类中的getItemCost方法。但是我得到一个错误,该方法不可见......我无法弄清楚错误:
public class Shopping_Basket {
private List<Merchandise> basket;
public List<Merchandise> getList() {
return basket;
}
public Shopping_Basket() {
basket = new ArrayList<Merchandise>();
}
public double getTotalCost() {
double j = 0;
for (int i = 0; i < this.getList().size(); i++){
j += basket.get(i).getItemCost();
}
return j;
}
这是商品类:
public class Merchandise {
private String item_name;
private int item_cost;
public Merchandise(String name, int cost) {
this.item_name = name;
this.item_cost = cost;
}
public String getItemName() {
return item_name;
}
public double getItemCost() {
return item_cost;
}
getTotalCost()方法中的错误,它说getItemCost()不可见...帮助?
答案 0 :(得分:3)
您的代码很好,实际编译并执行正常。请参阅下文并交叉检查您是否做得对(我刚刚添加了main()
方法以执行您的代码):
$ cat > Merchandise.java
public class Merchandise {
private String item_name;
private int item_cost;
public Merchandise(String name, int cost) {
this.item_name = name;
this.item_cost = cost;
}
public String getItemName() {
return item_name;
}
public double getItemCost() {
return item_cost;
}
}
$ cat > Shopping_Basket.java
import java.util.ArrayList;
import java.util.List;
public class Shopping_Basket {
private List<Merchandise> basket;
public List<Merchandise> getList() {
return basket;
}
public Shopping_Basket() {
basket = new ArrayList<Merchandise>();
}
public double getTotalCost() {
double j = 0;
for (int i = 0; i < this.getList().size(); i++) {
j += basket.get(i).getItemCost();
}
return j;
}
public static void main(String[] args) {
Shopping_Basket sb = new Shopping_Basket();
System.out.println(sb.getTotalCost());
}
}
$ javac Shopping_Basket.java
$ java Shopping_Basket
0.0
所以,正如我所说,正如你所看到的,代码很好。对于编译器,至少因为有几点要指出:
Merchandise
中,item_cost
是int
,但getItemCost()
返回double
Shopping_Basket
的名称应修改为ShoppingBasket
答案 1 :(得分:1)
我没有看到任何错误,这段代码应该编译并且实际上在我的计算机上编译。 请尝试在IDE中清理项目,然后再次编译整个项目。
答案 2 :(得分:0)
课程是正确的。该方法是公开的,因此它是可见的。 可能是设置类路径或导入类的问题。
public class Merchandise {
private String item_name;
private int item_cost;
public Merchandise(String name, int cost) {
this.item_name = name;
this.item_cost = cost;
}
public String getItemName() {
return item_name;
}
public double getItemCost() {
return item_cost;
}
}
import java.util.ArrayList;
import java.util.List;
public class Shopping_Basket { 私人清单篮子;
public List<Merchandise> getList() {
return basket;
}
public Shopping_Basket() {
basket = new ArrayList<Merchandise>();
}
public double getTotalCost() {
double j = 0;
for (int i = 0; i < this.getList().size(); i++) {
j += basket.get(i).getItemCost();
}
return j;
}
public void addMerchandise(Merchandise m){
basket.add(m);
}
public static void main(String[] args) {
Merchandise m1 = new Merchandise("prova", 11);
Merchandise m2 = new Merchandise("prova2", 13);
Shopping_Basket sb = new Shopping_Basket();
sb.addMerchandise(m1);
sb.addMerchandise(m2);
System.out.println(sb.getTotalCost());
}
}