Push Down Automata program in java for Equal no of a's and b's

import java.io.*;
class pda
{
public static void main(String args[])throws IOException
{
String s;
int i;
int pass=0;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter String");
s=in.readLine();
char ar[]=s.toCharArray();
Stack ob=new Stack();
for(i=0;i<s.length();i++)
{
if(ar[i]=='a')
ob.push(ar[i]);
else
{
if(pass>0)
ob.pop(ar[i]);
else
{
pass++;
System.out.println();
System.out.println("\nSkiping First b in String");
}
}
}
ob.check(s.length());
}
}

class Stack
{
int i=0;
int top=0;
char stack1[]=new char[20];

void push(char a)
{
stack1[top]='x';
System.out.print("\npush X for a");
System.out.print("\tStack->");
for(i=top;i>=0;i--)
{
System.out.print(" "+stack1[i]);
}
top++;
}

void pop(char b)
{
top--;
System.out.print("\npop X for b");
System.out.print("\tStack->");
for(i=top-1;i>=0;i--)
{
System.out.print(" "+stack1[i]);
}
}
void check(int n)
{
int count=0;
for(int z=0;z<20;z++)
if(stack1[z]=='x')
{
count++;
}
if(count==(n/2))
System.out.println("\n\nit is PDA");
else
System.out.println("\n\nit is not PDA");
}
}
/*
OUTPUT:
E:\>java pda
Enter String
aaabbbb

push X for a Stack-> x
push X for a Stack-> x x
push X for a Stack-> x x x

Skiping First b in String

pop X for b Stack-> x x
pop X for b Stack-> x
pop X for b Stack->

it is PDA */

You may also like...

2 Responses

  1. panda says:

    This code is terrible, do not use it. Incomplete loop expressions, referring to out-of-scope variables, irregular single/double quotes, wanton use of newlines, and horrible formatting to top it all off. Even if this code does somehow work, you'd have to put in an hour or two to clean it up and make it usable. As it is currently, it's not even good enough to turn in for homework.

Leave a Reply

Your email address will not be published. Required fields are marked *