Escaped quote issue in Java questions

Escaped quote issue in Java questions

por Anton Dil -
Número de respuestas: 1

Hi Richard,

I seem to have found a new issue with the java_class template, i.e.  

{{ STUDENT_ANSWER | replace({'public class ': 'class ' }) }} 

public class __tester__ {

    public static void main(String[] args) {
        __tester__ main = new __tester__();
        main.runTests();
    }

    public void runTests() {
        {{ TEST.testcode }};
    }
}

A simple test case is to create a question and have the student answer include an escaped quotation mark, e.g. if the answer is something like this

public class X
{
    String s = "\"";
}

It seems to be the escaped quote (\") character that causes the issue, although using template debugging the produced output compiles fine outside of Coderunner. The same error occurs if the Answer uses this character 

We get
NO_PUBLIC_CLASS_FOUND.java:6: error: class __tester__ is public, should be declared in a file named __tester__.java

public class __tester__ {

It is a small thing, but I am not sure how to fix it. e('java') isn't helping.  The issue doesn't seem to affect the test fields.

Anton

En respuesta a Anton Dil

Re: Escaped quote issue in Java questions

por Anton Dil -
I have a fix for this using a Python template, which is to use Python raw strings for the student_answer and the __tester__.java classes, and not use e('py') at all. I haven't worked out how to do it using the java_class template yet.

So my new template has

student_answer = r"""{{ STUDENT_ANSWER }}"""

and

with open("__tester__.java", "w") as f:
f.write(r"""
public class __tester__ { // etc

This also solves the issue for test cases, which otherwise fail when you use escaped characters. The problem isn't just with \" but also with \\ and \n inside a string.

This approach probably doesn't work if the student uses triple quotes (text blocks) in Java, which has been available in java for a while now.