Home      Affiliated Colleges      Course content      First Sem     Second Sem     Third Sem     Fourth Sem     Fifth Sem     Sixth Sem     Seventh Sem     Eighth Sem     Lab report 4th sem     Contact    

Monday, April 25, 2011

Compiler Design and construction: Write the java code to implement DFA accepting odd numbers of zeros :

 

Q. Write the java code to implement DFA accepting odd numbers of zeros :

==========================================================================
Solution:
package nfa;

import java.util.Scanner;

/**
 *
 * @author vkpandey
 */
public class Main {

    /**
     * @param args the command line arguments
     */

    static int i,s,s0=0,s1=1,s2=2,s3=3,s4=4,h=5,flag;
    static String str;
    public static int move1(int s, char c)
    {
          
            if(c =='a')
            {
                System.out.println("State S2");
                return s2;

            }
            else
                return h;

       
    }
    public static int move2(int s, char c)
    {
           if(c =='b')
            {
                System.out.println("State S4");
                return s4;

            }
            else
                return h;
       
    }
    public static void main(String[] args) {
        // TODO code application logic here
       
        int len, s;
        System.out.println("Enter the string:");
        Scanner input = new Scanner(System.in);
        str = input.next();
        len = str.length();
        s = s0;
        char c;
        System.out.println("State S0");
        if(str.charAt(0)=='a')
        {
         flag = s1;
         System.out.println("State S1");
        }
        else
        {
         flag = s3;
         System.out.println("State S3");
        }

        for(int i=0;i<len;i++)
        {
            c = str.charAt(i);
            if(flag == s1)
                s = move1(s,c);
            else
                s = move2(s,c);
        
        }
        if(s == s2 || s == s4)
            System.out.println("string accepted");
        else
            System.out.println("machine halt, string not accepted");


    }

}
Output:



1 comment:

  1. Nice post..!! I want to suggest a C program to implement DFA in another interesting way..!! Must visit.. It will be useful!!

    http://vipinnpillai.blogspot.com/2011/08/dfa-simulator.html

    ReplyDelete

^ Scroll to Top Related Posts with Thumbnails ^ Go to Top