-1

I am trying to make this program write the Ran.java file and us it in the same run time. But because the file is not made yet the java error checking is making it so I can not make a object of it in my code. Is there a way to make it so the file can be wrighten and used in the same run?

import java.io.File;  
import java.io.IOException; 
import java.io.FileWriter;
class Main {
 public static void main(String[] args) {
    try {
      File myObj = new File("Ran.java");
      if (myObj.createNewFile()) {
        System.out.println("File created: " + myObj.getName());
          FileWriter my = new FileWriter("Ran.java");
        my.write(""" 
import java.util.Random;
class Ran {
Random ran = new Random();
  int makeRint(int N, int M){
int a = ran.nextInt(M + N - 1) + N;
    return a;
  }
} 
                 """);
        my.close();
        run();
      } 
      else {
        run();
      }
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }

  public static void run(){
Ran a = new Ran();
System.out.println(a.makeRint(1, 35));
    
  }
}


If I take out the instantiation of the Ran object and the call to it's US method I am able to run the file and add it in after, but I don't want to edit the .java file manuely. Even if there is a way to run the Ran.java file on the secound run through without editing Main.java that would be great.

1 Answers1

1

You can not because Java is not an interpreted language. You have to compile first the source code into bytecode, then execute the bytecode with the Java runtime. If that works for you then you could do that programmatically, by using the Java Compiler API then loading the classes in a JAR file dynamically. You can search for that topic, there should be plenty of answers.

aled
  • 21,330
  • 3
  • 27
  • 34