Ryan H
Ryan H

Reputation: 85

Trouble with Lists

I have a method setTopping(String topping) which takes a String as a parameter. Adds the String to a List, and depending what the String is, sets a value. eg salami 0.6, fungi 0.5 etc.

Now I have a List of Strings. It might contain 1, 2, 3 or 4 Strings. I want to add, in turn, the first String to the chooseTopping() method, then the second string, then, if there is one, the 3rd string.

However after adding 3 toppings, I got the output:

  [0.6]
  [salami]
  [0.6, 0.7]
  [salami, bacon]
  [0.6, 0.7, 0.5]
  [salami, bacon, fungi]

When I was expecting:

  [0.6, 0.7, 0.5]
  [salami, bacon, fungi]

What would be the best way to iterate through a list of an unknown quantity of Strings, and add them one by one to a method which takes Strings as a parameter?

Many Thanks

EDIT the print statements were in the for loop, thats why the output was multiplied

Upvotes: 0

Views: 55

Answers (1)

Balazs Gunics
Balazs Gunics

Reputation: 2077

Move these prints after the for:

for(int i = 0 ; i < toppings.size() ; i++){ 
    t.setTopping( toppings.get(i)  );
    }
    System.out.println( t.getCost() );
    System.out.println( t.getTopping() );
    System.out.println( b.getBase() );

I think that these getcost and gettopping will always print the full list, but you want to print only 1 time at the end.

Upvotes: 1

Related Questions