Java Question on code conversion

Java Question on code conversion

by Patrick Wang -
Number of replies: 2

Dear all,

I'd like to ask how to create a question that can ask student to convert an given if/else statement code to switch statement, or a given While loop code to For loop?

After I read through the documentation, I think I need to conduct two tests: 

  1. Firstly, use template grader to test the content of the student code to see whether it contains "switch... case"
  2. Then, test the code using Java_statement question type.

However, is it possible to combine these two tests in one question? It is quite troublesome to get students to put the their answers into two question answer boxes to check the correctness. 

Thanks.


Patrick


In reply to Patrick Wang

Re: Java Question on code conversion

by Richard Lobb -

Hi Patrick

It's certainly best to avoid splitting questions into two when possible, and in this case it's fairly straightforward.

For one-off questions, you can just customise the template so that before running/calling the student's code it checks it for the disallowed constructs. For example, here's a simple modification to the Java Write a method template to check that the student's code does not contain a for statement. 

public class Main {

    {{ STUDENT_ANSWER }}

    public static void main(String[] args) {
        Main main = new Main();
        String answer = "{{ STUDENT_ANSWER | e('java')}}";
        if (answer.contains("for")) {
            System.err.println("You answer contains 'for'!");
        } else {
            main.runTests();
        }
    }

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

A typical such question and its output might be as follows.

Screen shot

If however they just copied the input method, they'd get:

Screen shot #2

A more sophisticated version would parse, or at least tokenize, the student's answer rather than just check for the substring "for".

If you're asking many questions of this sort, you'd be better of defining a new question type that uses template parameters to specify what constructs are required and what are forbidden. Most authors seem to wind up using Python for scripting such question types; see for example Peter Sander's question types elsewhere on this forum.

In reply to Richard Lobb

Re: Java Question on code conversion

by Patrick Wang -

Hi Richard, 

Your reply is very informative and helpful.

Thanks a lot.


Regards,

Patrick