10 Oct 2012

finding synonyms and hyponyms for words in java

/* finding synonyms and hyponyms for words in java */

import edu.smu.tspell.wordnet.NounSynset;
import edu.smu.tspell.wordnet.Synset;
import edu.smu.tspell.wordnet.SynsetType;
import edu.smu.tspell.wordnet.WordNetDatabase;

public class wordnet 
{
    String a[]=new String[2];
    public static void wordnet(String a[])
    {
        int j=0;
        while(j<2)
        {
        
            System.setProperty("wordnet.database.dir", "C:\\Program Files\\WordNet\\2.1\\dict");
            NounSynset nounSynset;
            NounSynset[] hyponyms;
            WordNetDatabase database = WordNetDatabase.getFileInstance();
            Synset[] synsets = database.getSynsets(a[j], SynsetType.NOUN);
             System.out.println("*********************************************");
            for (int i = 0; i < synsets.length; i++)
                {
            nounSynset = (NounSynset)(synsets[i]);
            hyponyms = nounSynset.getHyponyms();
           
            System.err.println(nounSynset.getWordForms()[0] +": " + nounSynset.getDefinition() + ") has " + hyponyms.length + " hyponyms");
           
                }
            j++;
        }
         System.out.println("*********************************************");
    }

}

DFS in java with example

//DFS in java with example, Depth first search(DFS) in java example code, dfs program in java

import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;
import weiss.nonstandard.PriorityQueue;
import weiss.nonstandard.PairingHeap;
import weiss.nonstandard.BinaryHeap;

// Used to signal violations of preconditions for
// various shortest path algorithms.
class GraphException extends java.lang.RuntimeException
{
    public GraphException(java.lang.String name)
    {
        super(name);
    }
}

// Represents an edge in the graph.
class Edge
{
    public Vertex     dest;   // Second vertex in Edge
    public double     cost;   // Edge cost
    
    public Edge( Vertex d, double c )
    {
        dest = d;
        cost = c;
    }
}

// Represents an entry in the priority queue for Dijkstra's algorithm.
class Path implements Comparable
{
    public Vertex     dest;   // w
    public double     cost;   // d(w)
    
    public Path( Vertex d, double c )
    {
        dest = d;
        cost = c;
    }
    
    public int compareTo( Object rhs )
    {
        double otherCost = ((Path)rhs).cost;
        
        return cost < otherCost ? -1 : cost > otherCost ? 1 : 0;
    }
}

// Represents a vertex in the graph.
class Vertex
{
    public String     name;   // Vertex name
    public List       adj;    // Adjacent vertices
    public double     dist;   // Cost
    public Vertex     prev;   // Previous vertex on shortest path
    public int        scratch;// Extra variable used in algorithm

    public Vertex( String nm )

      { name = nm; adj = new LinkedList( ); reset( ); }

    public void reset( )

      { dist = Graph.INFINITY; prev = null; pos = null; scratch = 0; }    
      
    public PriorityQueue.Position pos;  // Used for dijkstra2 (Chapter 23)
}

public class Graph
{
    public static final double INFINITY = Double.MAX_VALUE;
    private Map vertexMap = new HashMap( ); // Maps String to Vertex

    /**

     * Add a new edge to the graph.
     */
    public void addEdge( String sourceName, String destName, double cost )
    {
        Vertex v = getVertex( sourceName );
        Vertex w = getVertex( destName );
        v.adj.add( new Edge( w, cost ) );
    }

    /**

     * Driver routine to handle unreachables and print total cost.
     * It calls recursive routine to print shortest path to
     * destNode after a shortest path algorithm has run.
     */
    public void printPath( String destName )
    {
        Vertex w = (Vertex) vertexMap.get( destName );
        if( w == null )
            throw new NoSuchElementException( "Destination vertex not found" );
        else if( w.dist == INFINITY )
            System.out.println( destName + " is unreachable" );
        else
        {
            System.out.print( "(Cost is: " + w.dist + ") " );
            printPath( w );
            System.out.println( );
        }
    }

    /**

     * If vertexName is not present, add it to vertexMap.
     * In either case, return the Vertex.
     */
    private Vertex getVertex( String vertexName )
    {
        Vertex v = (Vertex) vertexMap.get( vertexName );
        if( v == null )
        {
            v = new Vertex( vertexName );
            vertexMap.put( vertexName, v );
        }
        return v;
    }

    /**

     * Recursive routine to print shortest path to dest
     * after running shortest path algorithm. The path
     * is known to exist.
     */
    private void printPath( Vertex dest )
    {
        if( dest.prev != null )
        {
            printPath( dest.prev );
            System.out.print( " to " );
        }
        System.out.print( dest.name );
    }
    
    /**
     * Initializes the vertex output info prior to running
     * any shortest path algorithm.
     */
    private void clearAll( )
    {
        for( Iterator itr = vertexMap.values( ).iterator( ); itr.hasNext( ); )
            ( (Vertex)itr.next( ) ).reset( );
    }

    /**

     * Single-source unweighted shortest-path algorithm.
     */
    public void unweighted( String startName )
    {
        clearAll( ); 

        Vertex start = (Vertex) vertexMap.get( startName );

        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        LinkedList q = new LinkedList( );

        q.addLast( start ); start.dist = 0;

        while( !q.isEmpty( ) )

        {
            Vertex v = (Vertex) q.removeFirst( );

            for( Iterator itr = v.adj.iterator( ); itr.hasNext( ); )

            {
                Edge e = (Edge) itr.next( );
                Vertex w = e.dest;
                if( w.dist == INFINITY )
                {
                    w.dist = v.dist + 1;
                    w.prev = v;
                    q.addLast( w );
                }
            }
        }
    }

    /**

     * Single-source weighted shortest-path algorithm.
     */
    public void dijkstra( String startName )
    {
        PriorityQueue pq = new BinaryHeap( );

        Vertex start = (Vertex) vertexMap.get( startName );

        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        clearAll( );

        pq.insert( new Path( start, 0 ) ); start.dist = 0;
        
        int nodesSeen = 0;
        while( !pq.isEmpty( ) && nodesSeen < vertexMap.size( ) )
        {
            Path vrec = (Path) pq.deleteMin( );
            Vertex v = vrec.dest;
            if( v.scratch != 0 )  // already processed v
                continue;
                
            v.scratch = 1;
            nodesSeen++;

            for( Iterator itr = v.adj.iterator( ); itr.hasNext( ); )

            {
                Edge e = (Edge) itr.next( );
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( cvw < 0 )
                    throw new GraphException( "Graph has negative edges" );
                    
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist +cvw;
                    w.prev = v;
                    pq.insert( new Path( w, w.dist ) );
                }
            }
        }
    }

    /**

     * Single-source weighted shortest-path algorithm using pairing heaps.
     */
    public void dijkstra2( String startName )
    {
        PriorityQueue pq = new PairingHeap( );

        Vertex start = (Vertex) vertexMap.get( startName );

        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        clearAll( );

        start.pos = pq.insert( new Path( start, 0 ) ); start.dist = 0;

        while ( !pq.isEmpty( ) )

        {
            Path vrec = (Path) pq.deleteMin( );
            Vertex v = vrec.dest;
                
            for( Iterator itr = v.adj.iterator( ); itr.hasNext( ); )
            {
                Edge e = (Edge) itr.next( );
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( cvw < 0 )
                    throw new GraphException( "Graph has negative edges" );
                    
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist + cvw;
                    w.prev = v;
                    
                    Path newVal = new Path( w, w.dist );                    
                    if( w.pos == null )
                        w.pos = pq.insert( newVal );
                    else
                        pq.decreaseKey( w.pos, newVal ); 
                }
            }
        }
    }

    /**

     * Single-source negative-weighted shortest-path algorithm.
     */
    public void negative( String startName )
    {
        clearAll( ); 

        Vertex start = (Vertex) vertexMap.get( startName );

        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        LinkedList q = new LinkedList( );

        q.addLast( start ); start.dist = 0; start.scratch++;

        while( !q.isEmpty( ) )

        {
            Vertex v = (Vertex) q.removeFirst( );
            if( v.scratch++ > 2 * vertexMap.size( ) )
                throw new GraphException( "Negative cycle detected" );

            for( Iterator itr = v.adj.iterator( ); itr.hasNext( ); )

            {
                Edge e = (Edge) itr.next( );
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist + cvw;
                    w.prev = v;
                      // Enqueue only if not already on the queue
                    if( w.scratch++ % 2 == 0 )
                        q.addLast( w );
                    else
                        w.scratch--;  // undo the enqueue increment    
                }
            }
        }
    }

    /**

     * Single-source negative-weighted acyclic-graph shortest-path algorithm.
     */
    public void acyclic( String startName )
    {
        Vertex start = (Vertex) vertexMap.get( startName );
        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        clearAll( ); 

        LinkedList q = new LinkedList( );
        start.dist = 0;
        
          // Compute the indegrees
        Collection vertexSet = vertexMap.values( );
        for( Iterator vsitr = vertexSet.iterator( ); vsitr.hasNext( ); )
        {
            Vertex v = (Vertex) vsitr.next( );
            for( Iterator witr = v.adj.iterator( ); witr.hasNext( ); )
                ( (Edge) witr.next( ) ).dest.scratch++;
        }    
            
          // Enqueue vertices of indegree zero
        for( Iterator vsitr = vertexSet.iterator( ); vsitr.hasNext( ); )
        {
            Vertex v = (Vertex) vsitr.next( );
            if( v.scratch == 0 )
                q.addLast( v );
        }    
       
        int iterations;
        for( iterations = 0; !q.isEmpty( ); iterations++ )
        {
            Vertex v = (Vertex) q.removeFirst( );

            for( Iterator itr = v.adj.iterator( ); itr.hasNext( ); )

            {
                Edge e = (Edge) itr.next( );
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( --w.scratch == 0 )
                    q.addLast( w );
                
                if( v.dist == INFINITY )
                    continue;    
                
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist + cvw;
                    w.prev = v;
                }
            }
        }
        
        if(iterations!=vertexMap.size())
            throw new GraphException("Graph has a cycle!");
    }

    public static boolean processRequest(java.io.BufferedReader in,Graph g)

    {
        String startName=null;
        String destName=null;
        String alg=null;

        try

        {
System.out.print("Enter start node:");
            if((startName=in.readLine())==null)
                return false;
            System.out.print("Enter destination node:");
            if((destName=in.readLine())==null)
                return false;
            System.out.print("Enter algorithm (u, d, n, a ):");   
            if((alg=in.readLine())==null)
                return false;
            
            if(alg.equals("u"))
                g.unweighted(startName);
            else if(alg.equals("d"))    
            {
                g.dijkstra(startName);
                g.printPath(destName);
                g.dijkstra2(startName);
            }
            else if(alg.equals("n"))
                g.negative(startName);
            else if(alg.equals("a"))
                g.acyclic(startName);
                    
            g.printPath(destName);
        }
        catch(java.io.IOException e)
          { 
           System.err.println(e); 
          }
        catch(NoSuchElementException e)
          { 
           System.err.println(e); 
          }          
        catch(GraphException e)
          { 
          System.err.println(e); 
          }
        return true;
    }

    /**

     * A main routine that:
     * 1. Reads a file containing edges (supplied as a command-line parameter);
     * 2. Forms the graph;
     * 3. Repeatedly prompts for two vertices and
     *    runs the shortest path algorithm.
     * The data file is a sequence of lines of the format source destination.
     */
    public static void main(String []args)
    {
        Graph g=new Graph();
        try
        {
            java.io.FileReader fin=new java.io.FileReader(args[0]);
            java.io.BufferedReader graphFile=new java.io.BufferedReader(fin);
            java.lang.String line;
            while((line=graphFile.readLine())!=null)
            {
                java.util.StringTokenizer st=new java.util.StringTokenizer(line);

                try

                {
                    if(st.countTokens()!=3)
                    {
                        System.err.println("Skipping ill-formatted line"+line);
                        continue;
                    }
                    String source=st.nextToken();
                    String dest=st.nextToken();
                    int cost=java.lang.Integer.parseInt(st.nextToken());
                    g.addEdge(source,dest,cost);
                }
                catch(java.lang.NumberFormatException e )
                  { 
                  System.err.println("Skipping ill-formatted line"+line); 
                  }
             }
         }
         catch(java.io.IOException e)
           { 
            System.err.println(e); 
           }

         System.out.println("File read");

         System.out.println(g.vertexMap.size()+"vertices");

         java.io.BufferedReader in=new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

         while(processRequest(in,g));
    }
}


graph.txt

D C 10
A B 12
D B 23
A D 87
E D 43
B E 11
C A 19


Running Procedure:
c:\>java classname graph.txt

For ieee projects visit our site here

Text To Speech In Java Source Code

/* Text To Speech In Java Source Code, text to speech converter in java source code, text to speech in java, text to speech in java example */

import com.sun.speech.freetts.*;
import java.io.* ;
public class tts
{
private String speaktext;
public void dospeak(String speak,String voice)
{
speaktext=speak; 
try
{
VoiceManager voiceManager=VoiceManager.getInstance();
Voice voices=voiceManager.getVoice(voice);
Voice voices1[]=voiceManager.getVoices();
System.out.println("Available Voices");
for(int i=0;i<voices1.length;i++)
System.out.println(voices1[i].getName());
Voice sp=null;
if(voices!=null)
{
sp=voices; 
}
else
{
System.out.println("No Voice Available");
}
sp.allocate();
sp.speak(speaktext);
sp.deallocate();
}
catch(Exception e)
{
e.printStackTrace();
}

public static void main(String[] args)
{
String name=null;
//int value=0;
tts obj=new tts();
InputStreamReader istream=new InputStreamReader(System.in) ;
BufferedReader bufRead=new BufferedReader(istream) ;
try 
{
while(!("stop").equals(name))
{
//char c=(char)value;
name=bufRead.readLine();
//if(c==' ')
obj.dospeak(name,"kevin16");
//name=""+c;
}
}
catch(IOException err) 
{
System.out.println("Error reading line");
}
}
}

For ieee projects visit our site here

26 Sept 2012

Converting a number into its equivalent value in words in Java

/* Converting a number into its equivalent value in words in Java,  How to convert a number into words using Java */

class constNumtoLetter
  {
      String[] unitdo={""," One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine", " Ten", "       Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen",  " Seventeen"," Eighteen","Nineteen"};
      String[] tens={"","Ten"," Twenty"," Thirty"," Forty"," Fifty"," Sixty"," Seventy"," Eighty"," Ninety"};
      String[] digit={""," Hundred"," Thousand"," Lakh"," Crore"};
      int r;
      //Count the number of digits in the input number
      int numberCount(int num)
      {
          int cnt=0;
          while (num>0)
          {
            r=num%10;
            cnt++;
            num=num/10;
          }
            return cnt;
      }
      //Method for Conversion of two digit
      String twonum(int numq)
      {
           int numr,nq;
           String ltr="";
           nq=numq/10;
           numr=numq%10;
           if(numq>19)
             {
           ltr=ltr+tens[nq]+unitdo[numr];
             }
           else
             {
           ltr=ltr+unitdo[numq];
             }
           return ltr;
      }
      //Method for Conversion of three digit
      String threenum(int numq)
      {
             int numr,nq;
             String ltr="";
             nq=numq/100;
             numr=numq%100;
             if(numr==0)
              {
              ltr=ltr+unitdo[nq]+digit[1];
               }
             else
              {
              ltr=ltr+unitdo[nq]+digit[1]+" and"+twonum(numr);
              }
             return ltr;
      }
}

 class originalNumToLetter

   {
      public static void main(String[] args) throws Exception
      {
          //Defining variables q is quotient, r is remainder
          int len,q=0,r=0;
          String ltr=" ";
          String Str="Rupees:";
          constNumtoLetter n=new constNumtoLetter();
          int num=Integer.parseInt(args[0]);
          if(num<=0) 
 System.out.println("Zero or Negative number not valid for conversion");
          while(num>0)
          {
             len=n.numberCount(num);
             //Take the length of the number and do letter conversion
             switch(len)
             {
                  case 8:
                          q=num/10000000;
                          r=num%10000000;
                          ltr=n.twonum(q);
                          Str=Str+ltr+n.digit[4];
                          num=r;
                          break;

                  case 7:

                  case 6:
                          q=num/100000;
                          r=num%100000;
                          ltr=n.twonum(q);
                          Str=Str+ltr+n.digit[3];
                          num=r;
                          break;

                  case 5:

                  case 4:
                           q=num/1000;
                           r=num%1000;
                           ltr=n.twonum(q);
                           Str=Str+ltr+n.digit[2];
                           num=r;
                           break;

                  case 3:

                            if(len== 3)
                            r=num;
                            ltr=n.threenum(r);
                            Str=Str+ltr;
                            num=0;
                            break;

                  case 2:

                        ltr=n.twonum(num);
                           Str=Str+ltr;
                           num=0;
                           break;

                  case 1:

                           Str=Str+n.unitdo[num];
                           num=0;
                           break;
                  default:
                          num=0;
                          System.out.println("Exceeding Crore....No conversion");
                          System.exit(1);
              }
                          if (num==0)
                          System.out.println(Str+" Only");
            }
         }
      }


 Output:

 D:\Crawlerf1>java originalNumToLetter 10560090
  Rupees: One Crore Five Lakh Sixty Thousand Ninety Only

25 Sept 2012

Calling multiple methods in java

/* Calling multiple methods in java */ 

for (int i=0;i<N;i++) 
      {
      try {
        obj.getClass().getMethod("method"+i).invoke(obj);
           } 
     catch (Exception e) 
        {
         // give up
         break;
      }
    }


ex:
obj.method1()
obj.method2()
obj.method3()
obj.method4()
obj.method5()

jdbc odbc connection for ms access in java

/* jdbc odbc connection for ms access in java code, jdbc-odbc connection in java with ms-access*/ 
import static java.lang.System.*;
import java.sql.*;

public class DBDemo
{
    public static void main(String[] args)
    {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String sourceURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=UserDB.mdb;";
            Connection userDB = DriverManager.getConnection(sourceURL, "admin", "");
            Statement myStatement = userDB.createStatement();
            String writeString = "INSERT INTO Users(Firstname,Surname,Id)                     
            VALUES('Fred','Bloggs','bf01')";
            myStatement.executeUpdate(writeString);

            ResultSet results = myStatement.executeQuery("SELECT Firstname, Surname, Id FROM Users 
            ORDER BY Id");

            while (results.next())
            {
                out.print(results.getString(1) + " ");
                out.print(results.getString(2) + " ");
                out.println(results.getString(3));
            }
            results.close();
        }
        //The following exceptions MUST be caught
        catch(ClassNotFoundException cnfe)
        {
            out.println(cnfe);
        }
        catch(SQLException sqle)
        {
            out.println(sqle);
        }
    }
}

append new line on top of the jtextarea in java swing

/* how to insert or append new line on top of the jtextarea in java swing */
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;

public class TestTextArea {

    private void initUI() {
        JFrame frame = new JFrame("textarea example");
        final JTextArea textarea = new JTextArea(24, 80);
        JButton addText = new JButton("Add new line");
        addText.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try { 
                    textarea.getDocument().insertString(0,"New line entered      on"+new Date()+"\n",null);
                     } 

                catch (BadLocationException e1) 
                    {
                    e1.printStackTrace();
                   }
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(textarea));
        frame.add(addText, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                new TestTextArea().initUI();
            }
        });
    }

}