Search code examples
javalistjgrasp

Is there a way to make a user list?


For my coding class I have to build a shopping list by having the user enter the number of items they need and then each item (one at a time). I then have to output the final shopping list in a multi-line dialogue box (one item per line). I have the first two parts done where users enter the number of items and what items they would like, but can't figure out how to output all the items. Any help would be great, thanks! Also, I am using jgrasp and we don't use println to output messages.

I've tried Output.showMessage("Shopping list \n" + items); and Output.showMessage(items.toString());

public class ShoppingList
    {
        public static void main (String [] args)
        { 

          String items;
          int numItems, count;

          numItems = Input.readInt("Enter number of items: ");

          count = 0;
          while (count < numItems)
          {

             items = Input.readString("Enter item: ");

             count = count + 1;


          }//end while

          Output.showMessage(items.toString());      

       } //end main
    } //end ShoppingList

The output should show a list of user entered items like:

Shopping List: Bananas Milk


Solution

  • Items cannot be of string type because whenever the line

    items = Input.readString("Enter item: ");
    

    is executed, the previous value of items is overwritten.
    If you are allowed to for your homework, it's ideal to make items an array otherwise you would have to change the previous statement to

    items += Input.readString("Enter item: ");
    items += '\n';
    

    Note:items here is one long String.