0

I just have a basic Class encapulating foods, and when i go to my client class to check the method getName, String and all the other methods, it all returns null. Not sure what is wrong here.

 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());
    }
}
WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
sfinger
  • 45
  • 5

1 Answers1

4

This is a typo:

Foods(String n, int c, int s){
    n = name;
    c = calPerServing;
    s = servingPerContainer;
}

Should be:

Foods(String n, int c, int s){
    name = n;
    calPerServing = c;
    servingPerContainer = s;
}
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93