Objectivo
Cree un traductor básico de C# a Java.
Debe aceptar archivos de origen de C# y crear un archivo de origen Java equivalente. Recibirá el nombre del archivo en la línea de comandos, y debe traducir al menos:
"Main()" en "main( String[] args )"
"string" en "String"
"bool" en "booleano"
"Console.WriteLine" en "System.out.println"
" : " en " se extiende " si está en la misma línea que la palabra "clase" (y cualquier otra mejora que se le ocurra, como el manejo de cadenas o la conversión de una línea de lectura en un bloque de prueba-captura).
Ejemplo Ejercicio C#
Mostrar Código C#
// Importing necessary namespaces
using System; // Importing the System namespace for basic C# functionality
using System.IO; // Importing the IO namespace for file operations
using System.Text.RegularExpressions; // Importing the Regex class for regular expressions
public class CSharpToJavaTranslator
{
// Method to translate C# code to Java code
public static void TranslateCSharpToJava(string inputFile, string outputFile)
{
// Open the input C# file for reading
using (StreamReader reader = new StreamReader(inputFile)) // Open the input file in read mode
{
// Open the output Java file for writing
using (StreamWriter writer = new StreamWriter(outputFile)) // Open the output file in write mode
{
string line; // Declare a string to store each line from the C# file
// Read each line from the C# file until the end
while ((line = reader.ReadLine()) != null)
{
// Translate C# specific syntax to Java equivalents
line = TranslateMainMethod(line); // Translate the Main method
line = TranslateDataTypes(line); // Translate data types
line = TranslateConsoleWriteLine(line); // Translate Console.WriteLine to System.out.println
line = TranslateClassDeclaration(line); // Translate class declaration with inheritance
line = TranslateReadLineToTryCatch(line); // Translate Console.ReadLine to a try-catch block in Java
// Write the translated line to the Java file
writer.WriteLine(line); // Write the translated line into the Java file
}
}
}
}
// Translate "Main()" to "main(String[] args)"
private static string TranslateMainMethod(string line)
{
// Use a regular expression to replace Main() with main(String[] args)
return Regex.Replace(line, @"Main\(\)", "main(String[] args)");
}
// Translate C# data types to Java data types
private static string TranslateDataTypes(string line)
{
// Replace "string" with "String" and "bool" with "boolean" to match Java's types
line = line.Replace("string", "String"); // Replace string type
line = line.Replace("bool", "boolean"); // Replace bool type
return line; // Return the modified line
}
// Translate "Console.WriteLine" to "System.out.println"
private static string TranslateConsoleWriteLine(string line)
{
// Replace Console.WriteLine with System.out.println
return line.Replace("Console.WriteLine", "System.out.println");
}
// Translate ": " to " extends " if it's part of the class declaration
private static string TranslateClassDeclaration(string line)
{
// If the line contains "class" and ":", change ": " to " extends "
if (line.Contains("class") && line.Contains(":")) // Check if it's a class declaration with inheritance
{
line = line.Replace(":", "extends"); // Replace : with extends for Java inheritance syntax
}
return line; // Return the modified line
}
// Translate "Console.ReadLine()" to a try-catch block in Java
private static string TranslateReadLineToTryCatch(string line)
{
// If the line contains Console.ReadLine, replace it with a try-catch block for Java input
if (line.Contains("Console.ReadLine()")) // Check if Console.ReadLine() is in the line
{
line = "try {\n" + // Start of try block
" String input = System.console().readLine();\n" + // Read input from console
"} catch (Exception e) {\n" + // Catch any exception that occurs
" System.out.println(\"Error reading input\");\n" + // Display an error message if input fails
"}"; // End of try-catch block
}
return line; // Return the modified line
}
}
class Program
{
// Main method where the program execution starts
static void Main(string[] args)
{
// Checking if the user provided the file names
if (args.Length < 1) // Check if there is at least one argument
{
Console.WriteLine("Please provide the input C# file."); // Prompt user to provide the input file
return; // Exit the program if no file is provided
}
string inputFile = args[0]; // Assign the input file name from the command line argument
string outputFile = Path.ChangeExtension(inputFile, ".java"); // Generate the output file name by changing the extension to .java
// Checking if the input file exists
if (!File.Exists(inputFile)) // Check if the input file exists
{
Console.WriteLine($"The file {inputFile} does not exist."); // Print error if file does not exist
return; // Exit the program if the file does not exist
}
// Calling the translation method
CSharpToJavaTranslator.TranslateCSharpToJava(inputFile, outputFile); // Call the method to translate the C# file to Java
Console.WriteLine($"C# file '{inputFile}' has been successfully translated to Java and saved as '{outputFile}'."); // Notify the user that the translation is complete
}
}
Salida
dotnet run example.cs
C# file 'example.cs' has been successfully translated to Java and saved as 'example.java'.
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp