I am trying to write a program that acts as an automatic grader that will
- run a student's java file
- write it's output to a text file
- test that text file against another text file with the desired output
I haven't gotten past step 1 as when the BufferedReader gets to a line where the student program is waiting for the user to give input, it will not advance. I understand that I need to provide input, and I have created a BufferedWriter to provide it, but it's not taking it the way I expect it to. Let's say I have this file as the student's program:
import java.util.Scanner;
public class studentProgramTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter any word: ");
String word = in.next();
System.out.println("The word is " + word);
}
}
What I have so far for the auto grader is
public class hw3Grader {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
String program = "studentProgramTest.java";
runProcess("java " + program);
} catch (Exception e) {
System.out.println(e);
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
InputStreamReader stdout = new InputStreamReader(pro.getInputStream());
OutputStreamWriter stdin = new OutputStreamWriter(pro.getOutputStream());
BufferedReader in = new BufferedReader(stdout);
BufferedWriter writer = new BufferedWriter(stdin);
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
if (line.contains("Enter any word:")) {
writer.write("test\r");
writer.flush();
writer.close();
}
}
}
}
From what I can discern, the reader is stuck between System.out.print("Enter any word: "); and String word = in.next(); as what I have noticed is that if I change System.out.print("Enter any word: "); to System.out.println("Enter any word: "); I am able to write a value for input and I get the output of the program. I've been thinking that maybe what I actually need to do, is check the line of code rather than the printed output. I have found this post to turn the InputStream into a String, and tried option 3, but it's still getting stuck at the same line, I'm assuming. I feel like there is something I am unaware of on how the code is actually working, so if anyone can provide any insight, that would be great!
What I have written to recreate option 3:
Scanner s = new Scanner(pro.getInputStream());
while (s.hasNextLine()) {
if (s.nextLine().contains(".next()")) {
System.out.println("test");
}
}