Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

How to use Java or any code in LaTeX and refer it in my document?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Here is an example using the listings package. You use the label option to specify the label, and then refer to it using the usual \ref:

enter image description here

Notes:

  • Requires two runs to resolve the reference. In the first run you will see ??, and in the second this will get replaced with the actual listing number.

Code:

\documentclass{article}
\usepackage{filecontents}
\usepackage{listings}

\begin{filecontents*}{foo.java}
 public int nextInt(int n) {
     if (n<=0)
        throw new IllegalArgumentException("n must be positive");

     if ((n & -n) == n)  // i.e., n is a power of 2
         return (int)((n * (long)next(31)) >> 31);

     int bits, val;
     do {
         bits = next(31);
         val = bits % n;
     } while(bits - val + (n-1) < 0);
     return val;
 }
\end{filecontents*}


\lstdefinestyle{MyListStyle} {
    numbers=left,
    numberstyle=\small,
    language=Java
    }
\begin{document}
\lstinputlisting[
    style=MyListStyle,
    linerange={2-6},
    firstnumber=2,
    caption={Partial Listing},
    label={lst: partial}
    ]{foo.java}

As can be seen from Listings~\ref{lst: partial} we see that...
\end{document}
share|improve this answer
1  
A nice addition to this would be to also explain how one refers to lines within a listing (use the escapechar or mathescape listings options; in the listing itself escape to LaTex and place a \label commands in the respective line). –  Daniel Mar 8 '12 at 16:29
1  
@Daniel: I think it is better to use the line number instead. Otherwise you have to alter the actual code snippet that you are referring to. –  Peter Grill Mar 8 '12 at 16:52
    
Right, didn't notice on first sight that you are using \lstinputlisting. –  Daniel Mar 8 '12 at 20:00
    
I am just getting ?? what ever times i run the script..Am i missing anything? –  volatNumbers Mar 9 '12 at 8:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.