Solved

Help on logic

Posted on 2001-06-06
9
171 Views
Last Modified: 2010-03-31
I have a string which have the product code|quantity|@price
and separate by a "#" for each set. Example:

A123|20|2.99#B444|9|1.20#.........and so on.

but now, the user will add several set of string to this existing string, and the product code will be duplicate, so I would like to add the quantity for the same product code. For example the user input the:

N934|18|6.00#V245|6|0.00#A123|10|2.99#......

so the final output string will be:
A123|30|2.99##B444|9|1.20#N934|18|6.00#V245|6|0.00

Please help with sample code for how to do it. Thanks !!
0
Comment
Question by:clo1
9 Comments
 
LVL 1

Expert Comment

by:LDC
ID: 6159197
You can use StringTokenizer to cut your string in bits between the #, then between the |.
You then get lists of strings for item/price/quantity.
Store the items in a Hashtable, convert the quantity string to a int (Integer.parseInt if I remember well). Then put the Integer into the Hashtable as a value if there was no value, else sum the values to get the new Integer.
Now, what if your user types A123|10|29.9# which is a different price? How do you know which price is correct?
Your user should probably never have to type strings like that.
Why don't you give them a panel where they put a list of article/quantity? You could more easily generate your String afterwards.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 6159205
What you want is a class like this:

class Product
{
  public String id ;
  public int amount ;
  public double price ;

  public Product( String prodString )
  {
    StringTokenizer st = new StringTokenizer( "|" ) ;
    int pos = 1 ;
    while( st.hasMoreTokens() )
    {
      String element = st.nextToken() ;
      switch( pos )
      {
        case 1 :
          id = element ;
          break ;
        case 2 :
          amount = Integer.parseInt( element ) ;
          break ;
        case 3 :
          price = Double.parseDouble( element ) ;
          break ;
      }
      pos++ ;
    }
  }

  public boolean isEqual( Object o )
  {
    if( o instanceof Product )
    {
      return ((Product)o).id.equals( this.id ) ;
    }
    return false ;
  }

  public String toString()
  {
    return id + "|" + amount + "|" + price ;
  }

  public addAmount( Product p )
  {
    this.amount += p.amount ;
  }
}

Create a Vector (call it v).

then use a String tokenizer (like above) to split the string at the "#" characters, and create a product by calling the constructor with this string (call it p)...

then, if v.indexOf( p ) finds the product with that id already exists in the vector (returns a position grater than -1 -- call that pos )

do:

((Product)v.elementAt( pos )).addAmount( p ) ;

Then at the end, step through all of the elements in your vector, and output them with a hash between them...

String str = "" ;
for( int i = 0 ; i < v.size() ; i++ )
{
  str += ((Product)v.elementAt( i )).toString() ;
  if( i < v.size() - 1 ) str += "#" ;
}

Good luck...

Tim.
0
 

Expert Comment

by:DanVan
ID: 6159238
Ah, I see a load of people have answered, but here goes.
This should demo the idea of having a system that should be flexible enough to allow you to change product prices easily, build a nice GUI on it, whatever you want.
Use Tim's post to see how to parse the strings to extract the info if needed.

Good luck
Dan

just paste the below into a file called "Test.java" and run it to see if it is the sort of thing you are looking for.
-------------------
import java.util.*;

public class Test {
     public static void main(String[] args) {
          Orders o = new Orders();
          Products p = new Products();
         
          p.add( new Product("A0123", 2.2f) );
          p.add( new Product("B0123", 1.2f) );
          p.add( new Product("C0123", 0.2f) );
         
          //retrieve the product for a given string:
          Product prod;
          prod = p.find("A0123");
          o.addOrder(prod, 3);

          prod = p.find("B0123");
          o.addOrder(prod, 1);

          prod = p.find("A0123");
          o.addOrder(prod, 2);
         
          prod = p.find("XXXX");
          if (prod == null) {
               System.out.println("Invalid product entered");
          }else {
               o.addOrder(prod, 3);
          }
         
          //Print the orders as one long string
          System.out.println(o);          
     
          //change the price of one of the products:
          prod = p.find("B0123");
          prod.price = 5.5f;
         
          //add another order:
          prod = p.find("B0123");
          o.addOrder( prod, 10 );

          //Print the orders as one long string
          System.out.println(o);          
     
     }
     
     
}

class Product {
     public String code;
     public float price;
     
     Product(String code, float price) {
          this.code = code;
          this.price = price;
     }
}

class Products {
     Hashtable allProducts = new Hashtable();
     
     public void add( Product p ) {
          allProducts.put(p.code, p );
     }
     
     public Product find( String code ) {
          Product p = (Product)allProducts.get( code );
          return p;
     }
}


class Orders {
     Hashtable allOrders = new Hashtable();
     
     public void addOrder(Product prod, int quantity) {
          int num = 0;
          Integer numInt = (Integer)allOrders.get(prod);
          if (numInt != null) {
               num = numInt.intValue();
          }
          num += quantity;
          allOrders.put(prod, new Integer(num));
     }
     
     public int getOrder(Product prod) {
          int num = 0;
          Integer numInt = (Integer)allOrders.get(prod);
          if (numInt != null) {
               num = numInt.intValue();
          }
          return num;    
     }
     
     public String toString() {
          int max = allOrders.size() - 1;
          StringBuffer buf = new StringBuffer();
          Iterator it = allOrders.entrySet().iterator();

          while (it.hasNext()) {
              Map.Entry e = (Map.Entry) (it.next());
               Product prod = (Product)e.getKey();
              buf.append(prod.code +"|"+ e.getValue() +"|"+ prod.price +"#");
          }
          return buf.toString();
     }
}
0
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
LVL 3

Accepted Solution

by:
chrisos earned 100 total points
ID: 6159247
Yeah, more code!

Chrisos

/////////////////////////////////////////////////////

package com.wintermuteis;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Arrays;

public class Summation extends Object {

     private static class Product extends Object {
          String name = null;
          int quantity = 0;
          float cost = 0f;

          Product(String name, int initialQuantity, float cost) {
               this.name = name;
               this.quantity = initialQuantity;
               this.cost = cost;
          }

          void incrementQuantity( int additionalQuantity ) {
               quantity += additionalQuantity;
          }
     }

     public static String summarize(String source) {
          Hashtable allProducts = new Hashtable();
          StringTokenizer products = new StringTokenizer(source, "#");
          StringTokenizer values = null;
          String currentProduct = null;
          String currentValue = null;
          String name = null;
          int quantity = 0;
          float cost = 0f;
          int valueCounter = 0;
          while( products.hasMoreTokens() ) {
               currentProduct = products.nextToken();
               values = new StringTokenizer(currentProduct, "|");

               name = null;
               quantity = 0;
               cost = 0f;
               valueCounter = 0;

               while( values.hasMoreTokens() ) {
                    currentValue = values.nextToken();
                    switch( valueCounter ) {
                         case 0:
                              name = currentValue;
                              break;
                         case 1:
                              quantity = Integer.parseInt(currentValue);
                              break;
                         case 2:
                              cost = Float.parseFloat(currentValue);
                              break;
                    }
                    valueCounter++;
               }
               if( !allProducts.containsKey(name) ) {
                    Product newProduct = new Product(name, quantity, cost);
                    allProducts.put(name, newProduct);
               }
               else {
                    Product existingProduct = (Product)allProducts.get(name);
                    existingProduct.incrementQuantity(quantity);
               }
          }

          StringBuffer result = new StringBuffer();
          Enumeration keys = allProducts.keys();
          String[] keyNames = new String[allProducts.size()];
          int count = 0;
          while( keys.hasMoreElements() ) {
               keyNames[count] = (String)keys.nextElement();
               count++;
          }
          Arrays.sort(keyNames);

          Object key = null;
          Product outProduct = null;
          for( int i = 0; i < keyNames.length; i++ ) {
               key = keyNames[i];
               outProduct = (Product)allProducts.get(key);
               result.append(outProduct.name+"|"+outProduct.quantity+"|"+outProduct.cost+"#");
          }
          result.delete(result.length()-1,result.length()-1);
          return result.toString();;
     }

     public static void main(String[] args) {
          String test = "A123|20|2.99#B444|9|1.20";
          System.out.println("Test: "+test+" -> "+summarize(test));
          test = "A123|20|2.99#B444|9|1.20#N934|18|6.00#V245|6|0.00#A123|10|2.99";
          System.out.println("Test: "+test+" -> "+summarize(test));
     }
}
0
 
LVL 3

Expert Comment

by:chrisos
ID: 6159293
Mine does the decode, summarisation and encode, does than mean I'm the winnder? :)
0
 
LVL 35

Expert Comment

by:TimYates
ID: 6159524
My Product class is more contained ;-P

Hee hee!

Tim
0
 
LVL 35

Expert Comment

by:TimYates
ID: 6159531
;-)
0
 
LVL 3

Expert Comment

by:chrisos
ID: 6160736
Mine demonstrates encapsulation using inner classes!

(Although in all fairness I could have added a toString() to the inner class)

:P
0
 
LVL 35

Expert Comment

by:TimYates
ID: 6162969
Oh well, you win ;-)
0

Featured Post

Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
thymeleaf natural templating vs JSP 2 102
Java Server Faces parameter pass? 6 50
HSSFWorkbook cannot be resolved error 10 70
Adding multiple JVM environments to RedHat 6 7 23
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

809 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