Power JavaDeveloping Intelligent Systems With Java and Prolog

Listing 2. Interface between Java and Prolog.


/* A sample Java program that demonstrates the interfacing
* between Java and Prolog
 */
importamzi.ls.*;
class JavaProlog
{
   /**
    * the logic engine
    */
   LogicServer ls;

   /**
    * main program method. creates a JavaProlog object and passes
    * control to it
    */
   public static void main(String args[])
   {
      JavaProlog jp = new JavaProlog();
      jp.run();
   }

   /**
    * runs the prolog engine
    */
   public void run()
   {
      try
      {
         ls = new LogicServer();
         ls.Init("");

         ls.AddPred("result", 1, "JavaProlog", "result", this);
         ls.Load("amzi4.xpl");
         ls.ExecStr("consult(family)");
         ls.ExecStr("ancestors(tim)");
      }
      catch(LSException e)
      {
         e.printStackTrace();
         System.exit(1);
      }
   }

   /**
    * prints the term passed to this predicate
    * @return true if the printing succeeded
    */
   public boolean result()
	{
      String answer;
      boolean tf;

      try
      {
         long term = ls.GetParm(1);
         String result = ls.TermToStr(term, 200);
         System.out.println(result);
         
         return true;

      }
      catch (LSException e)
      {
         System.out.println(e.GetMsg());
         e.printStackTrace();
         return false;
      }
   }
}