0

I am writing a simple online judge, thus I need a way to test the code a user has written. The flow is as follows:

  1. User writes a program that tries to solve the task which was given to him. For example a program to calculate the square of a number.
  2. The program is then given an input file (to be precise there will be many such files for each test case there is one), for example input.txt and then the program generates some output(s) which will be tested against the expected output(s) to determine if everything is correct.

So let's say that an user has written the following code to solve a problem to find the square of a number:

import java.util.Scanner;

public class B {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        System.out.println(n * n);
    }
}

If I run this program from the terminal, I can do this:

$ javac B.java
$ java B < input.txt

Where for example input.txt contains:

5

The program will execute correctly. What I need to do now is to check that output against the correct output (that step isn't the problem). However I need to automate this task and for this I've read these answers:

The solution in [1] is preferred, however either solution fails to function properly, namely the issue is here:

// omitted most of the code for brevity, similar code as in [2]
public class A {

    public static void main(String[] args) {
        // Fails to pass input.txt to Scanner from class B i.e. that file is being ignored
        processRun = Runtime.getRuntime().exec("java B < input.txt");
    }
}

The issue is that input.txt is completely ignored here and that now the Scanner in class B is waiting indefinitely to receive an input. Is there a way to properly handle this i.e. to feed input.txt to class B through Java code?

aleks
  • 3
  • 1
  • Would it not be easier to write some JUnit tests and if they pass, the code would be correct? – Wim Deblauwe Sep 13 '22 at 14:40
  • That's not the solution I can go with, because there are potentially thousands of tasks and it has to be automated. Something similar to CodeForces that is. – aleks Sep 13 '22 at 14:43

2 Answers2

0

I have found a way to do it, albeit it's a workaround/hack:

// omitted most of the code for brevity, similar code as in [2]
public class A {

    public static void main(String[] args) {
        // Fails to pass input.txt to Scanner from class B i.e. that file is being ignored
        processRun = Runtime.getRuntime().exec("/bin/sh check.sh");
    }
}

echo `java B < input.txt`

Doing things this way works.

aleks
  • 3
  • 1
0

Maybe a little late. but try ProcessBuilder

 ProcessBuilder builder = new ProcessBuilder("java", "B");
 builder.redirectInput(new File("input.txt"));
 try {
         processRun = builder.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
Drl
  • 41
  • 4