Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Apachevelocity Calculation Example

Related Tutorials


 
 

Share on Google+Share on Google+

Calculation Example

Advertisement
This Example shows, how to calculate using velocity. This code displays the product name and their price with the total amount of all product.

Calculation Example

     

This Example shows, how to calculate using velocity. This code displays the product name and their price with the total amount of all product. 
Here in this code we have used method init() to initialize velocity, then create file template named "Product.vm". 

ProductList.java

package velocity.calculation;

import java.io.*;
import java.util.*;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class ProductList {

  public static void main(String args[]) throws Exception {
  Velocity.init();

  Template template = 
   Velocity.getTemplate
("./src/velocity/calculation/Product.vm");

  VelocityContext context = new VelocityContext();

  ArrayList list = new ArrayList();
  list.add(new Product("Product 1"111.99));
  list.add(new Product("Product 2"222.89));
  list.add(new Product("Product 3"333.79));
  list.add(new Product("Product 4"444.69));

  context.put("productList", list);

  Iterator iterator = list.iterator();

  Product p = null;
  double total = 0.00;
  
  while (iterator.hasNext()) {
  p = (Productiterator.next();
  total+=p.getPrice();
  }
  context.put("totalPrice"new Double(total));

  Writer writer = new StringWriter();
  template.merge(context, writer);

  System.out.println(writer);
  }
}

Product.java

package velocity.calculation;

public class Product {

  private String name;
  private double price;

  public Product(String name, double price) {
  this.name = name;
  this.price = price;
  }

  public void setName(String name) {
  this.name = name;
  }

  public String getName() {
  return name;
  }

  public void setPrice(double price) {
  this.price = price;
  }

  public double getPrice() {
  return price;
  }
}

Product.vm

#foreach($product in $productList)
$product.Name  $$product.Price
#end

Total Price: $$totalPrice

Output:

Product 1  $111.99
Product 2  $222.89
Product 3  $333.79
Product 4  $444.69

Total Price: $1113.36

Download code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 26, 2008

Related Tutorials

Discuss: Calculation Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Dishari De
March 15, 2013
java.lang.NullPointerException

java.lang.NullPointerException is what I am getting while running this code in eclipse...
DMCA.com