Question

As a JAVA teaching assistant, I get stuck with grading a lot of student's labs. A lot of these labs use a Scanner to get input from a user. Instead of repeated bashing numbers into the keyboard, is there a way I can utilize a heredoc to run all of the labs with the same input parameters without changing the student's code? What I have so far (which works for except the heredoc-esque code):

    #!/bin/bash

    for i in unzip/*; do
      echo $i
      javac $i/lab0/AddThree.java
      cd $i/lab0
      java AddThree <<EOF
        2
        3
        4
      EOF
      cd ../../..
    done

The code I'm trying to grade adds three integers that are provided by the user. unzip is the directory where each student has a folder (i.e. file structure is ./unzip/student/lab0/sourcecode.java)

Java gives:

    unzip/student
    Hello out there
    I will add three numbers for you
    Enter three whole numbers on a line : 
    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
        at java.util.Scanner.next(Scanner.java:1530)
        at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at AddThree.main(AddThree.java:10)
    ./lab0test: line 9: 2: command not found
    ./lab0test: line 10: 3: command not found
    ./lab0test: line 11: 4: command not found
    ./lab0test: line 12: EOF: command not found
Était-ce utile?

La solution

Your heredoc looks good except it will send the spaces at the start of each line. To get rid of those, you can either use -EOF and start each line of the heredoc with Tab characters, which will get stripped:

      cd $i/lab0
      java AddThree <<-EOF
TabTab2
TabTab3
TabTab4
TabTabEOF
      cd ../../..

Or unindent the heredoc contents. It's ugly, but it'll work.

      cd $i/lab0
      java AddThree <<EOF
2
3
4
EOF
      cd ../../..

Alternatively, if the input is short enough you could do it inline:

java AddThree <<< $'2\n3\n4'

(Using $'...' tells the shell to interpret \n escape sequences.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top