Skip to content

Instantly share code, notes, and snippets.

@nikhil-RGB
Last active April 9, 2024 17:41
Show Gist options
  • Save nikhil-RGB/fab95bc2ae6d2e54d81eea28d95b26f2 to your computer and use it in GitHub Desktop.
Save nikhil-RGB/fab95bc2ae6d2e54d81eea28d95b26f2 to your computer and use it in GitHub Desktop.
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();
}
}
@nikhil-RGB
Copy link
Author

nikhil-RGB commented Apr 4, 2024

Code for Experiment 9 CD Lab:

  • javac filename.java - run this command to compile your source code to bytecode.
  • Next, run java filename - This will use the JVM to convert your bytecode to machine executable code and execute it

Important

Install JDK 1.8 if you don't have JAVA on your system. Run java --version to check if you have it installed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment