Java: retrieving and printing out items from an arraylist using getters -


i writing program simulate system in coffee shop person takes orders of customers gives customer token number , enters system token number of customer along items s/he has ordered. recordorder function carries out operation allows order details input. order represented token id, tid, , arraylist of strings representing items in order.

here have done far:

import java.util.arraylist; import java.util.list; import java.util.scanner;   public class ques4 {     private static class order{      private int tid;      private int orderid;      private string itemname;      public order(int tid,string itemname){         this.tid=tid;         this.itemname=itemname;      }      public int gettid() {         return tid;     }      public void settid(int tid) {         this.tid = tid;     }      public string getitemname() {         return itemname;     }      public void setitemname(string itemname) {         this.itemname = itemname;     }      /*public string tostring(){         return "token num: "+gettid()+ " item name: "+getitemname();     }*/  }  public static void main(string[] args) {       arraylist<order> listofitems= new arraylist<order>();     recordorder(listofitems);   }      private static void recordorder(arraylist<order> listofitems){          int n, tnum;         int num_orders;         string item = null;          scanner sc= new scanner(system.in);          system.out.println("enter token number: ");         tnum= sc.nextint();          system.out.println("enter number of items token number: "+tnum);        n=sc.nextint();        sc.nextline();       system.out.println("enter items: ");      for(int i=0; i<n;i++){          item=sc.nextline();         }     listofitems.add(new order(tnum, item));    for(order list: listofitems){      system.out.println("token num: "+list.gettid()+ " item name: "+list.getitemname());}              }   } 

the problem last item enter being printed out,that is, suppose input token number 9, number of items 3 , item names cheesecake, burritos, tacos, tacos being printed out , output this:

token num: 9 item name: tacos

it should instead be:

token num: 9 item name: cheesecake burritos tacos

for(int i=0; i<n;i++){     item=sc.nextline();     listofitems.add(new order(tnum, item)); } 

your logic of adding items should inside loop. since adding outside loop, 1 element gets added(that last element)

edit: print required way:

system.out.print("token num: "+list.gettid()+ " item name:"); for(order list: listofitems){      system.out.print(" "+list.getitemname()); }    system.out.println(); 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -