Results 1 to 2 of 2
  1. #1
    LCounter is offline Member
    Join Date
    Apr 2011
    Posts
    1
    Rep Power
    0

    Default How do I create a String[2][20], with only 10 items

    I am working on a java class, and have been asked to create an inventory object of String[2][20] and fill it with only 10 things.

    The only way I can think to do this, is as follows, but, is there a better way?

    private String[][] inventory = {
    {"flashlight","0"},
    {"knife","0"},
    {"Swiss army knife", "0"},
    {"camera", "0"},
    {"notebook", "0"},
    {"lighter", "0"},
    {"lunchbox", "0"},
    {"jacket", "0"},
    {"cell phone", "0"},
    {"mp3 player", "0"},
    {"",""},
    {"",""},
    {"",""},
    {"",""},
    {"",""},
    {"",""},
    {"",""},
    {"",""},
    {"",""},
    {"",""}
    };

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    Shouldn't that be [20][2]?

    Do you have an Inventory class? I'd do something like this
    Java Code:
    class Inventory {
        private final int MAX = 20;
        private String[][] inventory = new String[MAX][2];
        private int items = 0;
    
        public void addItem(String description, String quantity) {
            if(items < MAX) {
                inventory[items][0] = description;
                inventory[items][1] = quantity;
                items++;
            } else {
                System.out.println("Inventory is full");
            }
        }
    }
    Alternatively you could have the method return boolean to reflect if the item was added or not.

Similar Threads

  1. Best way to create a group of String,Double?
    By ozzyman in forum New To Java
    Replies: 3
    Last Post: 04-19-2011, 11:22 AM
  2. How to create dynamic string object???
    By Stephen Douglas in forum New To Java
    Replies: 8
    Last Post: 04-12-2010, 02:35 AM
  3. create object with name from string
    By skandalouz in forum New To Java
    Replies: 7
    Last Post: 12-05-2009, 11:40 PM
  4. Problem extracting items from a string with separators
    By PepsiColaMola in forum New To Java
    Replies: 3
    Last Post: 04-24-2009, 08:30 PM
  5. create a formula from a string
    By lemon3 in forum New To Java
    Replies: 4
    Last Post: 07-18-2008, 09:24 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •