0

I'm trying to create a getCalories method in which I have to return a String together with an integer but I'm getting an error saying that one cannot be converted to another. How do I make this work?

package task14;

import java.util.ArrayList;

public class Meal {

    ArrayList<Ingredient> ingredient = new ArrayList<Ingredient>();

    public Meal() {};

    public Meal(ArrayList<Ingredient> ingredient) {
        this.ingredient = ingredient;
    }

    **public int getCalories() {
        return "This meal has" + Ingredient.numberOfCalories;
    }**

    public String toString() {

        return ingredient.toString();

    }
}
2
  • 2
    Return an object with the value as a String or an Integer if both are different, otherwise store as an Integer and use the toString method of Integer. Commented Apr 15, 2019 at 20:56
  • You could use a Map<String,Integer> but it's a bit of an overkill for what you are trying to do. Commented Apr 15, 2019 at 21:00

3 Answers 3

1

If you're trying to return a sentence such as "This meal has 10" then you need to change the return type of your method to String.

If you're trying to return both - don't. There's no reason why wherever you're calling getCalories can't place that snippet of text before whatever it's being used for.

As an aside, it doesn't seem to make much sense to just print the value of the calories for one Ingredient in a Meal class. Perhaps you mean to loop over all Ingredients and sum the calories before returning the total?

Sign up to request clarification or add additional context in comments.

Comments

0

First, on the method public int getCalories() I would change int by a String. Then in line return "This meal has" + Ingredient.numberOfCalories; after the token + You could parse to String the value of numberOfCalories with Integer.toString(Ingredient.numberOfCalories). It would be returning an string, hope it work for you.

Comments

0

If you need to return multiple values which may include different types, one way is to create a utility class with the appropriate type fields defined and have your method defined to return an instance of that type of class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.