Question

Convert Python to Java

def read_fsm(filename):
fh = open('fsm.txt','r')
contents = fh.readlines()
sigma = list(contents[0].rstrip().split(' '))
table = {}
n = int(contents[1])
for i in range(n):
table[i] = {}
final = list(map(int,contents[2].rstrip().split(' ')))
  
for line in contents[3:]:
fro,ip,to = line.split(' ')
fro = int(fro)
to = int(to)
table[fro][ip] = to
print(table)
fh.close()
return table,final
  
def runString(table,final,string):
current = 0
for i in string:
current = table[current][i]
if current in final:
print(string,'--> ACCEPT')
else:
print(string,'--> REJECT')
  
def readInput(table,final):
fh = open('Strings.txt','r')
for line in fh.readlines():
string = line.rstrip()
runString(table,final,string)
fh.close()
  
def main():
table,final = read_fsm('fsm.txt')
readInput(table,final)
  
main()

fsm - Notepad File Edit Format View He e a 1 1 b 2 2 a 3 2 b 3 3 a 4 3 b 4 4 a e 4 b eStrings-Notepad File Edit Format View Help ab ba aab bba

fsm - Notepad File Edit Format View He e a 1 1 b 2 2 a 3 2 b 3 3 a 4 3 b 4 4 a e 4 b e
Strings-Notepad File Edit Format View Help ab ba aab bba
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the answer below, I have mentioned all the details in the comments.

In Java, I have made all the required table and list as the class parameters so that they can be used across the methods, because in Java we can not return multiple values at the same time such as return table, final in python.

FSM.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//class FSM where the required methods are implemented
public class FSM {
    //table to store the transition table of the FSM
    int table[][];
    //List to Store the fianl states of the FSM
    ArrayList<Integer> finall;
    //List to store the variables of the FSM
    List<String> sigma;

    //read_fsm method
    public void read_fsm(String filename) throws IOException{
        //BufferedReader is used to read the content of the file
        BufferedReader br = new BufferedReader(new FileReader(filename));

        //For sigma of the FSM
        // line to store the content of the line read
        String line = br.readLine();
        //split the lien by spaces into array
        String [] arr = line.split(" ");
        //create list of sigma
        sigma = Arrays.asList(arr);

        //For number of states of the FSM
        line = br.readLine();
        //convert it to integer
        int n = Integer.parseInt(line);

        //For final states of the FSM
        line = br.readLine();
        //read the values in the temporary string array
        String[] temp = line.split(" ");
        //arraylist initialization
        finall = new ArrayList<>();
        //save the states as a integer value to the list
        for(int i=0;i<temp.length;i++){
            finall.add(Integer.parseInt(temp[i]));
        }

        //For transition table of the FSM
        table = new int[n][arr.length];
        //read line
        line = br.readLine();
        //while there are lines
        while(line!=null){
            //get the values and convert it to from , to and symbol accordingly
            String [] values = line.split(" ");
            int fro = Integer.parseInt(values[0]);
            int to = Integer.parseInt(values[2]);
            int ip = sigma.indexOf(values[1]);
            //set table entry to the to state value
            table[fro][ip] = to;
            //get the next line
            line = br.readLine();
        }
        //below is the code to print the transition table
        System.out.print("{");
        for(int i=0;i<table.length;i++){
            System.out.print(i +": {");
            for (int j = 0; j < table[0].length ; j++) {
                System.out.print("\'" + sigma.get(j) + "\': " + table[i][j]);
                if(j<table[0].length-1){
                    System.out.print(", ");
                }
            }
            System.out.print("}");
            if(i < table.length-1){
                System.out.print(", ");
            }
        }
        System.out.println("}");
        //close the file
        br.close();
    }
    public void runString(String str){
        int i;
        //set the current state as the 0
        int current = 0;
        //read each symbol of the string
        for(i=0;i<str.length();i++){
            //get the index of the symbol in the sigma list to access it's index in table
            int index = sigma.indexOf(str.charAt(i)+"");
            //update the current state based on the transition table
            current = table[current][index];
        }
        //check if the current state is in the list of finall state.
        if(finall.contains(current)){
            System.out.println(str + " --> ACCEPT" );
        }
        else{
            System.out.println(str + " --> REJECT" );
        }
    }

    public void readInput() throws IOException{
        //BufferedReader to read the file
        BufferedReader br = new BufferedReader(new FileReader("Strings.txt"));
        //get the line from strings file
        String line = br.readLine();

        //read till there are lines
        while(line!=null){
            //call the runString() method for each line
            runString(line);
            //get the next line
            line = br.readLine();
        }
        //close the file
        br.close();
    }
    public static void main(String[] args) throws IOException {
        //create object of the class FSM to use it's methods
        FSM obj = new FSM();
        //call the method read_fsm by passing the file name
        obj.read_fsm("fsm.txt");
        //call the method readInput to read the file Strings.txt
        obj.readInput();
    }
}

Output:

| C:\Program Files\Javaljdk1. 8.0-151\bin\java ↑ ↓ a--> REJECT b REJEcT ab RE 回 ba--> REJECT |@ aab --> REJECT bba-REJECT

I have used files the same as provided in the question.

Add a comment
Know the answer?
Add Answer to:
Convert Python to Java def read_fsm(filename): fh = open('fsm.txt','r') contents = fh.readlines() sigma...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT