【发布时间】:2015-11-22 17:44:59
【问题描述】:
背景信息:
我是一名高中生,目前正在学习 Java,所以如果我的代码有明显的缺陷/我不小心用代码重新发明了轮子,我深表歉意。
最近我一直致力于编写一种深奥的语言,并决定将其编写为一个解释器,将代码翻译成 Java,然后运行代码。我迈出的第一步是尝试创建一个可以编译和运行 java 程序的小程序。其中的大部分代码都是从另一篇文章中收集的,这是我看过的第三或第四篇文章: how to compile & run java program in another java program?
我在该线程上使用了第三个答案中的代码,最初认为它有效。不幸的是,当我尝试使用类的文件名运行代码以使程序在其自身内编译和运行时,程序失败了。
这是修改后的代码:
/**
*Functions printLines, Run, and parts of main came from stacks overflow
*originaly but modifications have been made
*https://stackoverflow.com/questions/4842684/how-to-compile-run-java-program-in-another-java-program
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
public class JTest
{
private static void printLines(String name, InputStream ins) throws Exception
{
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
while ((line = in.readLine()) != null)
{
//System.out.println(name + " " + line);
System.out.println(line);
}
}
private static int run(String command) throws Exception
{
System.out.println(command);//prints command
Process pro = Runtime.getRuntime().exec(command);
printLines(command, pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
// System.out.println(command + " exitValue() " + pro.exitValue());
return pro.exitValue();
}
public static void main(String args[])
{
System.out.println("Enter the name of the file you want to run: ");
Scanner cin = new Scanner(System.in);
String jFileName = cin.nextLine();
try
{
int k = run("javac " + jFileName + ".java");
if (k==0)
k=run("java " + jFileName);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
我还使用了另一个类:
public class Cout
{
public static void main(String args [])
{
System.out.println("Hello World");
}
}
在我的初始测试中...
输出:
Enter the name of the file you want to run:
输入:
Cout
输出:
javac Cout.java
java Cout
Hello World
这是我尝试从 JTest 运行 JTest 时发生的情况...
输出:
Enter the name of the file you want to run:
输入:
JTest
输出:
javac JTest.java
java JTest
Enter the name of the file you want to run:
输入:
Cout
在我输入此内容后,终端窗口上没有输出任何内容,这导致了我的主要问题:
为什么我的代码没有运行 Cout 类,我该如何解决? (最好以使我的代码与 linux 和 windows 兼容的方式)或者有人可以指出我的资源吗?
【问题讨论】:
-
请不要用
[ANSWERED]标记标题在答案旁边使用复选标记以接受正确的答案,您和回答者将获得一些代表点,并将向社区显示您找到了一个回答 -
我的错。我混淆了在这个论坛和另一个论坛之间标记问题的过程。
标签: java compilation