list - Java Adding Strings after end of first for loop -
i have list, appends depending on user input, example if type "lmo" add large pizza, mozzarella , olives list. if type "mhmo" add medium pizza, ham, mozzarella , olives list.
now want use loop, print list in format such as
large pizza mozzarella, olives, £8.90
the loop can print contents of list how add with
string after end of first loop.
currently code is:
for(int l = 0; l < words.size(); l++) { if (words.size() == 1) { system.out.println(words.get(l) + " no toppings "+ "£"+string.format("%.2f", total)); } else { system.out.println(words.get(0) + " " + words.get(1) + ", " + words.get(2) + ", "+ "£" + string.format("%.2f", total)); } } }
at moment it's assuming theres 3 items in list can vary. approach can use loop increment + use with
string.
you can either creata pizza class on override tostring
method.
but keep simple, answer based on have provided me. not best solution, better use stringbuilder, lets keep simple. looking simple loop ;)
list<string> words = new arraylist<string>(); words.add("large pizza"); words.add("mozzarella"); words.add("pepperoni"); words.add("olives"); double total = 8.9; string order = ""; if(words.size()>1){ order = words.get(0) + " "; for(int = 1; < words.size(); i++){ order += " " + words.get(i) + ", "; } order += "£"+string.format("%.2f", total); } system.out.println(order);
output:
large pizza mozzarella, pepperoni, olives, £8.90
Comments
Post a Comment