我只有一个基本的类包装食物,当我去我的客户端类检查方法getName
,String和所有其他方法时,它都返回null。不知道这里有什么问题。
public class Foods {
public String name;
public int calPerServing;
public int servingPerContainer;
Foods(String n, int c, int s){
n = name;
c = calPerServing;
s = servingPerContainer;
}
@Override
public String toString() {
return "Name: " + name + "\nCalories Per Serving: " + calPerServing
+ "\nServings Per Container: " + servingPerContainer;
}
public String getName() {
return name;
}
public int getCalPerServing() {
return calPerServing;
}
public int getServingPerContainer() {
return servingPerContainer;
}
public int getTotalCalories(){
return (calPerServing * servingPerContainer);
}
}
public class Client {
public static void main(String[] args) {
Foods chips = new Foods("chips", 10, 1);
System.out.println(chips.getName());
}
}
答案 0 :(得分:4)
这是一个错字:
Foods(String n, int c, int s){
n = name;
c = calPerServing;
s = servingPerContainer;
}
应该是:
Foods(String n, int c, int s){
name = n;
calPerServing = c;
servingPerContainer = s;
}