Last active
April 9, 2024 17:41
-
-
Save nikhil-RGB/fab95bc2ae6d2e54d81eea28d95b26f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class CodeGenerationForIf { | |
public static void main(String[] args) { | |
// Example input: if (x > 5) { y = x * 2; } | |
String condition = "x>8"; | |
String action = "y = y / 10;"; | |
// Generate code for the if statement | |
String generatedCode = generateIfCode(condition, action); | |
System.out.println("Generated code for if:"); | |
System.out.println(generatedCode); | |
String wCond="x<7"; | |
String wAction="y=y/8"; | |
String generatedWcode= generateWhileCode(wCond,wAction); | |
System.out.println("Generated Code for while:"); | |
System.out.println(generatedWcode); | |
} | |
public static String generateIfCode(String condition, String action) { | |
StringBuilder codeBuilder = new StringBuilder(); | |
// Add the if statement | |
codeBuilder.append("if (").append(condition).append(") {\n"); | |
// Add the action inside the if block | |
codeBuilder.append("\t").append(action).append("\n"); | |
// Close the if block | |
codeBuilder.append("}"); | |
return codeBuilder.toString(); | |
} | |
public static String generateWhileCode(String condition,String action) | |
{ | |
StringBuilder codeBuilder = new StringBuilder(); | |
// Add the while statement | |
codeBuilder.append("while (").append(condition).append(") {\n"); | |
// Add the action inside the while block | |
codeBuilder.append("\t").append(action).append("\n"); | |
// Close the while block | |
codeBuilder.append("}"); | |
return codeBuilder.toString(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code for Experiment 9 CD Lab:
javac filename.java
- run this command to compile your source code to bytecode.java filename
- This will use the JVM to convert your bytecode to machine executable code and execute itImportant
Install JDK 1.8 if you don't have JAVA on your system. Run
java --version
to check if you have it installed