I am writing a grading program that is going to grade assignments. My students have to use Scanner in one of their method. My grader is a separate class that calls the students' methods. When I call the method with the Scanner, it prompts me to enter some input ( as it should ). I would like my grading class to be able to call the method and automatically input some predetermined string as if it was typed by the user without the program halting or pausing.
Is there any way how to do it in Java?
Thank you in advance.
You could simply replace System.in
with your own input stream, perhaps a file that contains the input you wish to feed to the student's class.
Assuming the student's class looks like this:
import java.util.Scanner;
public class Student {
public String prompt() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter some input:");
return scanner.nextLine();
}
}
You could "grade" it like this:
import java.io.FileInputStream;
import java.io.IOException;
public class Grader {
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("replies.txt"));
Student student = new Student();
String reply = student.prompt();
assert reply.equals("reply");
}
}