skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Monday, April 22, 2013

Singly linked list with header - Data Structure

Posted by Admin at 12:34 PM – 0 comments
 




class OrderedList  {
   private int value;
   private OrderedList next;

// Note: No setValue() method or setNext() methods are provided, 
// since those could require reordering the list.
  
   public int getValue() {
       return value; }

   public OrderedList getNext() {
       return next; }

// If X is in the list, returns the previous node.
// If X is not in the list, returns the node for the greatest element less 
// than  X.

   public OrderedList searchBefore(int x) { // Locate node containing X
       OrderedList n = this;
       while (true) {
          if (n.next==null) return n;
          if (n.next.value >= x) return n;
          n = n.next;
         } 
      }

// Is element x in the list. Note the use of the left to right evaluation of 
// && (if the condition n.net != null is false, then the conjunction returns
// false without evaluating n.next.value=x.

   public boolean inList(int x) {
       OrderedList n = searchBefore(x);
       return n.next != null && n.next.value == x; }

// Adds x to the ordered list, if it is not already there.
   public void add(int x) {
       OrderedList n = searchBefore(x);
       if (n.next == null || n.next.value != x) {
           OrderedList newNode = new OrderedList();
           newNode.value = x;
           newNode.next = n.next;
           n.next = newNode;
         }
     }
       
// Deletes X from the ordered list, if it is there.

   public void delete(int x) {
       OrderedList n = searchBefore(x);
       if (n.next != null && n.next.value == x)
          n.next = n.next.next;
      }



   public String toString() {
          OrderedList a = next;
          String s = "[";
          while (a != null) {
             s = s + a.value + " ";
             a = a.next;
           }
         return s+ "]";
         }

   public static void main(String[] args) {
      OrderedList l = new OrderedList();
      l.add(31);
      l.add(41);
      l.add(59);
      l.add(26);
      l.add(53);
      l.add(58);
      l.add(37);
      l.delete(53);
      System.out.println(l.toString());
}
}



[ Read More ]
Read more...

Ordered array of ints with no repetition - Data Structure

Posted by Admin at 12:32 PM – 0 comments
 



public class OrderedArray {

   private int numElements = 0;
   private int[] elements;

// Constructor..Note: the caller has to provide the array of elements.
// This is because Java generics do not allow a call "elements = new T[100]".
//
   public OrderedArray(int[] elts) {
        elements = elts; }

   public int getNumElements() { return numElements; } 

   public int nth(int n) { // return the Nth element
       if (n < numElements) return elements[n]; else return -1; }
  
   public int first() { return nth(0); } 
   public int  last() { return nth(numElements-1); } 

//  search(X) returns the index where X is, if X is in the list.
//  Otherwise, it returns the index of the smallest number greater than X
   public int search(int x) {
       if (numElements==0) return 0;
       if (x <= first()) return 0;
       if (x > last()) return numElements;
       if (x == last()) return numElements-1;
       return search1(x,0,numElements-1); 
     }

// X is strictly between L and U.
   public int search1(int x,int l,int u) {
        if (u==l+1) return u;
        else {
           int m = (l+u)/2;
           if (x==elements[m]) return m;
           else if (x < elements[m]) return  search1(x,l,m);
           else return search1(x,m,u);
        }
     }

   public boolean inList(int x) {
       return (elements[search(x)]==x); }

   public void add(int x) {
      int i = search(x);
      if (elements[i] != x)  {
        for (int j = numElements; j>i; j--)
           elements[j]=elements[j-1];
        elements[i]=x;
        numElements++;
       }
     }

   public void delete(int x) {
      int i = search(x);
      if (elements[i] == x) {
        for (int j=i+1; j < numElements; j++)
          elements[j-1] = elements[j];
        numElements--;
      }
    }


   public String toString() {
      String s = "[";
      for (int i=0; i < numElements; i++)
         s = s + " " + elements[i];
      return s+"]";
   }

   public static void main(String[] args) {
      OrderedArray l = new OrderedArray(new int[100]);
      l.add(31);
      l.add(41);
      l.add(59);
      l.add(26);
      l.add(53);
      l.add(58);
      l.add(37);
      l.delete(53);
      System.out.println(l.toString());
      System.out.println(l.search(2));
      System.out.println(l.search(26));
      System.out.println(l.search(53));
      System.out.println(l.search(54));
      System.out.println(l.search(195));
}
}


[ Read More ]
Read more...
Friday, April 19, 2013

Stop Watch Program - To measure the amount of time to process each input

Posted by Admin at 3:46 PM – 0 comments
 

public class Stopwatch { 

    private final long start;

    public Stopwatch() {
        start = System.currentTimeMillis();
    } 

    // return time (in seconds) since this object was created
    public double elapsedTime() {
        long now = System.currentTimeMillis();
        return (now - start) / 1000.0;
    } 

}

[ Read More ]
Read more...
Saturday, November 3, 2012

Parse XML file using DOM

Posted by Raju Gupta at 12:00 AM – 0 comments
 

This code snippet explains about the parsing of the xml file using the DOM parser.


import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class XMLParser {

    /**
     * @param args
     * @throws IOException 
     * @throws SAXException 
     */
    
    public void GetXMLValue(String FileName){
    
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db         = dbf.newDocumentBuilder();
            File file                  = new File(FileName);
            
            if(file.exists()){
                Document doc = null;
                try {
                    doc = db.parse(file);
                }
                catch (SAXException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Element docelement1     = doc.getDocumentElement();
                
                System.out.println("Root element of the document: "
                        + docelement1.getNodeName());                
                //for commercial credit
                NodeList valueList1 = docelement1.getElementsByTagName("CommercialCredit");
                
                if (valueList1 != null && valueList1.getLength() > 0) {
                 
                    for (int i = 0; i < valueList1.getLength(); i++) {
                        
                        Node node = valueList1.item(i);
                        
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            
                            Element e = (Element) node;
                            NodeList nodeList = e.getElementsByTagName("DistSourceId");
                            System.out.println("DistSourceId: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());

                            nodeList = e.getElementsByTagName("MMSReferenceStartTime");
                            System.out.println("MMSReferenceStartTime: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());

                            nodeList = e.getElementsByTagName("MMSReferenceEndTime");
                            System.out.println("MMSReferenceEndTime: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());  
                        }                        
                     // for Credit result ---- added only 3 fields to test.....                        
                        
                        NodeList valueList2 = docelement1.getElementsByTagName("CreditResult");
                        if (valueList2 != null && valueList2.getLength() > 0) {
                            
                            for (int j = 0; j < valueList2.getLength(); j++) {
                                
                                Element e2 = (Element) node;
                                NodeList nodeList2 = e2.getElementsByTagName("MediaAssetId");
                                System.out.println("MediaAssetId: "
                                        + nodeList2.item(0).getChildNodes().item(0)
                                                .getNodeValue());
                                
                                nodeList2 = e2.getElementsByTagName("DetectedTime");
                                System.out.println("DetectedTime: "
                                        + nodeList2.item(0).getChildNodes().item(0)
                                                .getNodeValue());
                                
                                nodeList2 = e2.getElementsByTagName("DetectedSourceId");
                                System.out.println("DetectedSourceId: "
                                        + nodeList2.item(0).getChildNodes().item(0)
                                                .getNodeValue());  
                            }
                        }//if ends here
                    }  
                }
                else{
                    System.exit(1);
                }                    
            }
        }
        catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }         
    }    
    
    public static void main (String[] args) throws SAXException, IOException {
        // TODO Auto-generated method stub
        String str = "C:\Test\Mytestfile.xml";
        new XMLParser().GetXMLValue(str);

    }

}

[ Read More ]
Read more...
Friday, November 2, 2012

Listing Files and Directory Using Java

Posted by Raju Gupta at 9:30 PM – 0 comments
 

Lists Files and directory present in the system   

File dir = new File("directoryName"); 
 String[] children = dir.list();
  if (children == null) 
{      
// Either dir does not exist or is not a directory 
 }
 else 
{   
   for (int i=0; i < children.length; i++) 
{
          // Get filename of file or directory       
   String filename = children[i];     
 }
  }
   // It is also possible to filter the list of returned files.
  // This example does not return any files that start with `.'.  
FilenameFilter filter = new FilenameFilter() 
{      
public boolean accept(File dir, String name)
 {
          return !name.startsWith(".");    
  }
  };
  children = dir.list(filter);
   // The list of files can also be retrieved as File 
File[] files = dir.listFiles();   
// This filter only returns directories  
FileFilter fileFilter = new FileFilter()
 {

      public boolean accept(File file)
 {
          return file.isDirectory();   
   }
  };  
files = dir.listFiles(fileFilter); 


[ Read More ]
Read more...

To Capture screen shots using Java

Posted by Raju Gupta at 11:30 AM – 0 comments
 

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public void captureScreen(String fileName) throws Exception 
{
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();   
Rectangle screenRectangle = new Rectangle(screenSize);  
 Robot robot = new Robot();  
 BufferedImage image = robot.createScreenCapture(screenRectangle);  
 ImageIO.write(image, "png", new File(fileName)); 
}


[ Read More ]
Read more...

Extract a zip file in Java

Posted by Raju Gupta at 3:48 AM – 0 comments
 

The sole purpose of this program is how to extarct the content of a zip file in java.We start by opening an input stream to the compressed file and an output stream to the file where we want the content to be extracted.
After that we get the next entry of the zip file (and the only entry in this case) - test so it's not null, and then start reading the contents from the input stream and writing each chunk read to the output stream.
As usual we should clean up properly afterwards so we close the input and output streams.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ExtractingZipFile{

    /**
     * Extracts a zip file
     */
    public void extractZipFile() {
        
        try {
            String zipFileName = "file.zip";
            String extractedFileName = "extractedfile.txt";
            
            //Create input and output streams
            ZipInputStream inStream = new ZipInputStream(new FileInputStream(zipFileName));
            OutputStream outStream = new FileOutputStream(extractedFileName);
            
            ZipEntry entry;
            byte[] buffer = new byte[1024];
            int nrBytesRead;
            
            //Get next zip entry and start reading data
            if ((entry = inStream.getNextEntry()) != null) {
                while ((nrBytesRead = inStream.read(buffer)) > 0) {
                    outStream.write(buffer, 0, nrBytesRead);
                }
            }
                    
            //Finish off by closing the streams
            outStream.close();
            inStream.close();
            
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new ExtractingZipFile().extractZipFile();
    }
    
}


[ Read More ]
Read more...
Newer Posts Older Posts
Subscribe to: Posts ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger