Exercise
Pascal to java translator
Objetive
Create a basic Pascal to java translator. It will accept program such as:
example program;
var
i: integer;
max: integer;
begin
writeLn("How many times?");
readLn(max);
for i := 1 to max do
writeLn("Hola");
end.
The steps you must follow are:
Read from beginning to end a text file, whose name will be entered by the user in command line or in an interactive way: up to 2 points.
Dump the contents to another text file, whose name will be the same, but with ".cs" extension instead of ".pas": up to 4 points.
Replace "WriteLn" with "Console.WriteLine", " = "with "==", " := " with "=", simple quotes with double quotes, "begin" with "{" and "end;", "end.", "end" (in that order) with "}", : up to 6 points.
Replace "program x;" with "class x {" followed with "Main", Replace "readln(x)" with "x=Convert.ToInt32(Console.RadLine())" ("x" must be any other identifier): up to 8 points.
Eliminate "var" and replace "x: integer" with "int x" (but "x" must be any other identifier): up to 9 points. Give a proper format to "for": up to 10 points.
Create a compilable java source from the previous Pascal source and similar ones: up to 11 points.
Example Code
package PascalToCSharp;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
System.out.print("Enter name file: ");
String fileName = new Scanner(System.in).nextLine();
if ((new java.io.File(fileName)).isFile())
{
java.io.FileReader filePascal = new java.io.FileReader(fileName);
java.io.BufferedReader filePascalBufferedReader = new java.io.BufferedReader(filePascal);
java.io.FileWriter fileCSharp = new java.io.FileWriter(fileName.substring(0, fileName.length() - 3) + "cs");
String line;
do
{
line = filePascalBufferedReader.readLine();
if (line != null)
{
line = line.replace("writeLn", "Console.WriteLine");
line = line.replace(" = ", "==");
line = line.replace(" :=", "=");
line = line.replace("'", "\"");
line = line.replace("begin", "{");
line = line.replace("end;", "}");
line = line.replace("end.", "}");
line = line.replace("end", "}");
if ((line.contains("program ")) && (line.substring(line.length() - 1).equals(";")))
{
line = line.replace("program ", "class ");
line = line.replace(";", "\n{\n static void Main()\n{");
}
if (line.contains("readLn("))
{
line = line.replace("readLn(", "");
line = line.replace(");", "");
line += " = Convert.ToInt32(Console.RadLine());";
}
line = line.replace("var", "");
if (line.contains(": integer;"))
{
line = line.replace(": integer;", "");
line = "int " + line.trim() + ";";
}
/* if ((line.Contains("for ")) &&
(line.Contains(" to ")) &&
(line.Contains(" do ")))
{
line = line.Replace("for ", "for (");
line = line.Replace(" to", "");
line = "int " + line.Trim() + ";";
}
fileCSharp.write(line + System.lineSeparator());
}
} while (line != null);
filePascal.close();
fileCSharp.close();
}
}
}