Solved

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

Posted on 2006-10-22
11
282 Views
Last Modified: 2010-03-31
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
Comment
Question by:tristatefab
  • 3
  • 2
  • 2
  • +1
11 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 17783866
Yes, using a Map would be better

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

(where the values of the map are mutable integer classes)
0
 
LVL 9

Expert Comment

by:shinobun
ID: 17784565
Or simply using Integers,

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

And to get the final values,

map.get(ToysInventory[i])
0
 
LVL 8

Expert Comment

by:reach2piyush
ID: 17786240
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
 

Author Comment

by:tristatefab
ID: 17794430
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 86

Accepted Solution

by:
CEHJ earned 168 total points
ID: 17794436
Use an ArrayList, then you can vary the input
0
 
LVL 9

Assisted Solution

by:shinobun
shinobun earned 166 total points
ID: 17798637
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
 

Author Comment

by:tristatefab
ID: 17800877
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
 
LVL 8

Assisted Solution

by:reach2piyush
reach2piyush earned 166 total points
ID: 17800933
>>>>>
// 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
 
LVL 86

Expert Comment

by:CEHJ
ID: 17801564
loadToys can be simply

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

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now