Firstly as from the @D.B. commentary:
You might try using the JavaCompiler tool, however, it requires the JDK so if you're turning it in for extra credit make sure your instructor will run it using the JDK not the JRE
It would be possible to compile the while while you run your program. It would be something like:
- Read the file.
- Compose a valid Java application.
- Compile it.
- And start it to run on a new thread.
Now, basically you cannot write Java Standard Edition expressions on a file and load the to execute on run time. It is because all java statements must to be parsed and translated to Java Bytecodes and it can only be done before the program to starts running. Except the case where you construct another Java application, compile it and put it to run as a new application invocation, done by you or some Java System Call.
The only thing the Java Virtual Machine can run are Java Bytecodes. So, your text file is not translated to it, then they cannot run. Although, this is not true to languages as Python and Javascript due they do not need to be translated into Machine Language as Bytecodes for the Java virtual Machine and assembly code for the x86 or x64 processor architectures as languages as C++.
You solution is use a interpreted language as Python and Javascript, instead of a compiled languages as Java or C++. As pointed by @that other guy there is the scripting language BeanShell which is a Java-like scripting language, if you are interested to learn it.
References:
- https://en.wikipedia.org/wiki/Interpreted_language
- https://en.wikipedia.org/wiki/Compiled_language
- https://en.wikipedia.org/wiki/Scripting_language
My goal is to run the code from the test.txt and output the answer. How should I approach this?
Within Java, to achieve this goal you can parse the file using your own syntax rules. And as well stated by @Vince Emigh
You'd need some form of parsing and semantic analysis to do this. You are asking us how to write an interpreter, and seeing how you haven't even posted your attempt or specified a specific problem you are having when implementing this, this is faaar too broad
For your example, it would be like:
text.txt
1
2
+
Your Java Source Code file:
File file = new File("test.txt");
try
{
BufferedReader br = new BufferedReader( new FileReader( file ) )
int numbers[] = new int[10];
String line;
while( ( line = br.readLine() ) != null )
{
if( line.contains( "+" ) )
{
... do stuff
}
}
}
catch( FileNotFoundException e )
{
System.err.format("File does not exist \n");
}
finally
{
if( reader !=null )
{
reader.close();
}
}
References:
- How to read a large text file line by line using Java?
- https://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html
- https://docs.oracle.com/javase/7/docs/api/java/io/File.html
- Is there an eval() function in Java?