• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 326
  • Last Modified:

Making a Program More Efficient Using a Vector, Map, or something else

I have created the following code which runs fine, however; I know there must be a more efficient way to get the same output. I was told to investigate using a vector or map may be a better solution. I looked them up and really do not understand them at all. I have had very little Java training and was wondering if I could get some assistance starting me out with recommendations and maybe help me modify it to work another way. What it does is takes the order input information and sscans through it and prints out how many items of each item are being ordered. If the item is not listed it prints the qty as an unknown. Hope this makes sense.

public class ToysInventory
{
      // declare counters to keep track of the number of each type of toys
      private int ball, bat, bear, car, doll, game, glove, playstation, train, unknown;
     
      //stores the current inventory items
      private String[] ToysInventory = {"ball", "bat", "bear", "car", "doll", "game",
                                        "glove", "playstation", "train", "unknown"};
     
      // stores the ordered items
      private String[] OrderInputArray = {"bear", "train", "car", "ball", "doll", "ball", "train", "doll", "game",
                                          "train", "bear", "doll", "train", "car", "ball", "bat", "glove", "bat",
                                          "b", "doll", "bear", "ball", "doll", "bat", "car", "glove", "train",
                                          "doll", "bear"};
                                           
      // count the number of each type of toys in our inventory.
      // This method uses the "length" method on the array to get the number
      // of toys in the inventory.

      public void countToys()
      {
        // for loop scans through array elements and increments
        // counters for inventory items as necessary
        for (int i = 0; i < OrderInputArray.length; i++)
        {
            // if value equals ball then increment ball counter by 1
            if(OrderInputArray[i].equals("ball"))
            {
              ball++;      
            }
            // if value equals bat then increment bat counter by 1
            else if (OrderInputArray[i].equals("bat"))
            {
              bat++;
            }
            // if value equals bear then increment bear counter by 1
            else if (OrderInputArray[i].equals("bear"))
            {
              bear++;
            }
            // if value equals car then increment car counter by 1
            else if (OrderInputArray[i].equals("car"))
            {
              car++;
            }
            // if value equals doll then increment doll counter by 1
            else if (OrderInputArray[i].equals("doll"))
            {
              doll++;
            }
            // if value equals game then increment game counter by 1
            else if (OrderInputArray[i].equals("game"))
            {
              game++;
            }
            // if value equals glove then increment glove counter by 1
            else if (OrderInputArray[i].equals("glove"))
            {
              glove++;
            }
            // if value equals playstation then increment playstation counter by 1
            else if (OrderInputArray[i].equals("playstation"))
            {
              playstation++;
            }
            // if value equals train then increment train counter by 1
            else if (OrderInputArray[i].equals("train"))
            {
              train++;
            }
            else
            // if no inventory items are found, the item is unknown
            // the unknown counter is then incremented by 1
            {
              unknown++;
            }
        }  
      }

      // Print the name of each toy, followed by its count.
      // identify toys whose count exceeds five with a "*".
      // comments for first if statement are typical for the rest

      public void printItems()
      {
        // Prints a blank line
        System.out.println();
       
        // Prints Order Summary and a blank line
        System.out.println("Order Summary:" + "\n");
       
        //if ball value is greater than or equal to 5 then...
        if (ball >= 5)
        {
            // if statement is true print this...
            System.out.println(" * Ball: " + ball);
        }
        // if statement is not true do this...
        else
        {
            // if statement is not ture print this...
            System.out.println(" Ball: " + ball);
        }
       
        if (bear >= 5)
        {
            System.out.println(" * Bear: " + bear);
        }
        else
        {
            System.out.println(" Bear: " + bear);
        }
       
        if (car >= 5)
        {
            System.out.println(" * Car: " + car);
        }
        else
        {
            System.out.println(" Car: " + car);
        }
       
        if (doll >= 5)
        {
            System.out.println(" * Doll: " + doll);
        }
        else
        {
            System.out.println(" Doll: " + doll);
        }
       
        if (game >= 5)
        {
            System.out.println(" * Game: " + game);
        }
        else
        {
            System.out.println(" Game: " + game);
        }

        if (glove >= 5)
        {
            System.out.println(" * Glove: " + glove);
        }
        else
        {
            System.out.println(" Glove: " + glove);
        }
       
        if (playstation >= 5)
        {
            System.out.println(" * Playstation: " + playstation);
        }
        else
        {
            System.out.println(" Playstation: " + playstation);
        }
       
        if (train >= 5)
        {
            System.out.println(" * Train: " + train);
        }
        else
        {
            System.out.println(" Train: " + train);
        }
       
        if (unknown >= 5)
        {
            System.out.println(" * Unknown: " + unknown);
        }
        else
        {
            System.out.println(" Unknown: " + unknown);
        }
        //prints a blank line
        System.out.println();
      }

      // This is the main method of the class. It calls the methods of the class to

      // perform its job.

      public static void main (String [] args)
      {

      // instantiate a class of "toysInventory", then call its methods:
      // countToys and printItems.
     
        ToysInventory collection = new ToysInventory();
        collection.countToys();
        collection.printItems();        
      }
}
0
tristatefab
Asked:
tristatefab
  • 3
  • 2
  • 2
  • +1
3 Solutions
 
CEHJCommented:
Yes, using a Map would be better

map.get(OrderInputArray[i]).inc();

(where the values of the map are mutable integer classes)
0
 
shinobunCommented:
Or simply using Integers,

map.put(OrderInputArray[i], map.get(OrderInputArray[i]) + 1);

And to get the final values,

map.get(ToysInventory[i])
0
 
reach2piyushCommented:
To get you started, here is a more detailed code snippet

Map toyInventory = new HashMap();
 public void countToys()
      {
        // for loop scans through array elements and increments
        // counters for inventory items as necessary
        for (int i = 0; i < OrderInputArray.length; i++)
        {
                 Integer num = (Integer)toyInventory.get(OrderInputArray[i]);
                 if (num == null)
                {
                      toyInventory.put(OrderInputArray[i],new Integer(1));
                 }
                else
                {
                     toyInventory.put(OrderInputArray[i],num +1);
                }
         }
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
tristatefabAuthor Commented:
What is a more effective way of storing the order input array items. Should a linked list or vector be used and if so, can someone give me an example of how I might do this? I like the idea of the hashmap for the counting of the toys.
0
 
CEHJCommented:
Use an ArrayList, then you can vary the input
0
 
shinobunCommented:
Most implementations of List [1] will do.

List<String> orderInput = new ArrayList<String>(); // or LinkedList<String>() or Vector<String>() or whatever.  :)
orderInput.add("bear");
orderInput.add("train");
orderInput.add("car");
...

If you are using jdk 1.4 or worse, then you don't need the <String> part.

[1] http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html
0
 
tristatefabAuthor Commented:
Can someone please tell me where I am going wrong. The output of this version should be the same as the one above. Any help is greatly appreciated...


import java.util.*;

public class IT350_P3_TeamE_GP01 {
      
    // declare an array to hold our inventory of toys
    private String [] paramToys = {      "bear", "train", "car", "ball", "doll", "ball",
                                                    "train", "doll", "game", "train", "bear", "doll",
                                                    "train", "car", "ball", "bat", "glove", "bat", "b",
                                                    "doll", "bear", "ball", "doll", "bat", "car", "glove",
                                                    "train", "doll", "bear"};

    // This is the main method of the class. It calls the methods of the class to perform its job.
    public static void main (String[] args)
    {
        // instantiate a class and call its methods loadToye, countToys and printItems.
             IT350_P3_TeamE_GP01 toyInventory = new IT350_P3_TeamE_GP01();
             
        // declare a HashMap to hold the inventory counts
          HashMap<String, Integer> toyCount = new HashMap<String, Integer>();
          
        // declare an ArrayList to store the paramToys  
           ArrayList<String> toysOrdered = new ArrayList<String>();                        
           toyInventory.loadToys(toysOrdered);
          toyInventory.countToys(toysOrdered,toyCount);
          toyInventory.printItems(toyCount);
    }
   
    // load the toysOrdered arrayList
    public void loadToys(ArrayList<String> a)
    {
        // loop through the paramToys and add to ArrayList
             for (int i=1; i <paramToys.length; i ++)
             {                        
                 a.add(paramToys[i]);
           }                 
    }// end of loadToys method;
   
    // This method counts the number of each type of toys  in our inventory.
    public void countToys (ArrayList a, HashMap<String, Integer> h)
    {
          
          Iterator iter = a.iterator();
          
        // loop through the ArrayList          
          while (iter.hasNext())
        {                              
                String toyName = iter.next().toString();
                
            // check to see if the toy already exists in the map
                if (h.containsKey(toyName))      
                {
                // toy exist in the map, get its current count                      
                      int i = ((Integer) h.get(toyName)).intValue();      
                       increment its count
                      
                // save the incremented count for the toy
                      h.put(toyName, new Integer( i + 1));                  
                }
                else
                      h.put(toyName, 1);                      
          }                      
    } end of countToys method;

     Print the name of each toy, followed by its count. Identify toys whose count exceeds five with a "*".
    public void printItems(HashMap h)
    {
        // get the entries in the HashMap and put into a variable of type Set
          Set toyItems = h.entrySet();
          
        // get the iterator from the set                            
          Iterator i = toyItems.iterator();                                    
      
        // print a header
          System.out.println("Order Summary:");
          
        // print a blank line                  
          System.out.println();                                                      
          
        // loop through all of the items in the set
            while(i.hasNext())       
            {                                                
            // get the entry for this map
              Map.Entry toyItem = (Map.Entry) i.next();
              
            // get how many there are of this toy      
              Integer count =  (Integer) toyItem.getValue();
              
            // move the toy name into the displayText variable  
              String displayText = (String) toyItem.getKey();
              
            // put an asterisk before the toy name if there are more than of them
              if (count >= 5 ) {
                     displayText = "*" + displayText;                  
              }      
                else
                     displayText = " " + displayText;
                     
            //print the toy name and count
                 System.out.println(displayText + ": " + count);      
          }
          
         System.out.println();                                                
          
     }//end of printItems method
}
0
 
reach2piyushCommented:
>>>>>
// load the toysOrdered arrayList
    public void loadToys(ArrayList<String> a)
    {
        // loop through the paramToys and add to ArrayList
            for (int i=1; i <paramToys.length; i ++)
            {                    
               a.add(paramToys[i]);
          }              
    }// end of loadToys method;


Loop through 0 to paramtoys.length..


or Use Arrays.asList(paramToys) to get the List
0
 
CEHJCommented:
loadToys can be simply

a.addAll(Arrays.asList(paramToys));
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now