Although I'm not a fan of on-the-fly computation inside a document, here's a possible solution using BeanShell:
BeanShell is a small, free, embeddable Java source interpreter with
object scripting language features, written in Java. BeanShell
dynamically executes standard Java syntax and extends it with common
scripting conveniences such as loose types, commands, and method
closures like those in Perl and JavaScript.
There we go.
paulo@alexandria Sandbox$ ls
bsh.jar test.tex
My humble code:
\documentclass{article}
\usepackage{fancyvrb}
\makeatletter
\newcommand{\calljava}{\ttfamily\@@input|"java -cp bsh.jar bsh.Interpreter tmp.bsh"}
\makeatother
\newenvironment{java}
{\VerbatimOut{tmp.bsh}}
{\endVerbatimOut\calljava}
\begin{document}
My first code.
\vspace{2em}
\begin{java}
int addTwoNumbers(int a, int b) {
return a + b;
}
System.out.println(addTwoNumbers(10, 20));
\end{java}
\vspace{2em}
My second code.
\vspace{2em}
\begin{java}
for (int i = 1; i <= 10; i++) {
System.out.println("I like ducks!\\par");
}
\end{java}
\end{document}
Running with pdflatex --shell-escape test.tex
:
The idea is quite simple: get the body of the java
environment and add it to a temporary file named tmp.bsh
, run the interpreter from bsh.jar
passing the temporary file to be executed, and capture the output.
My good friend egreg mentioned that this code doesn't work with xetex
or luatex
, unless we write another auxiliary file and input it. Let's stick with pdflatex
for a while then. :)
Hope it helps. :)
printMyString()
to be replaced by the entire procedure, or just"Hello World"
?listings
does provide\lstinputlistings
which can input from a file and you can specify alinerange
. Alternatively, there's aliterate
replacement that you could use.\write18
) or use LuaTeX and it's build-in Lua interpreter.