2

is it possible to do something like the following in texlipse?

\documentclass{article}
\usepackage{listings}  
\begin{document}

\section{Title}
import java
\subsection{Subtitle}

I want to display some java result

\begin{lstlisting}   
 printMyString()       
\end{lstlisting}              
\end{document}

Where printMyString() is for example:

public String printMyString() {
return "Hello World";
}

thanks!

3
  • 2
    What should the output look like? Do you want the string 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 a linerange. Alternatively, there's a literate replacement that you could use.
    – Werner
    Commented Mar 1, 2013 at 16:15
  • I want only Hello World to be displayed, thanks
    – Franky
    Commented Mar 1, 2013 at 16:19
  • 2
    @Franky: That would require a TeX engine with a build-in JVM; such a beast doesn't exist yet. The best you can do is have TeX execute other programs and use their output (\write18) or use LuaTeX and it's build-in Lua interpreter. Commented Mar 2, 2013 at 10:40

1 Answer 1

10

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:

I like ducks!

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. :)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .