[Tex/LaTex] What’s a good way to insert very few lines of code

listings

I know about the listings package, but it seems that it can't be put where I want it to be (h in float).

And since I just maybe want to insert exactly one line of code, I really want it to be where I put it, is there a good way?

Best Answer

Option 1: Use the listings package

Simple configuration for LaTeX header (before \begin{document}):

\usepackage{listings}
\usepackage{color}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\lstset{frame=tb,
   language=Java,
   aboveskip=3mm,
   belowskip=3mm,
   showstringspaces=false,
   columns=flexible,
   basicstyle={\small\ttfamily},
   numbers=none,
   numberstyle=\tiny\color{gray},
   keywordstyle=\color{blue},
   commentstyle=\color{dkgreen},
   stringstyle=\color{mauve},
   breaklines=true,
   breakatwhitespace=true
   tabsize=3
   }

You can change default language in the middle of document with \lstset{language=Java}.

Example of usage in the document:

\begin{lstlisting}
  // Hello.java
  import javax.swing.JApplet;
  import java.awt.Graphics;

  public class Hello extends JApplet 
  {
    public void paintComponent(Graphics g) {
      g.drawString("Hello, world!", 65, 95);
    }    
  }
\end{lstlisting}

Here's the result:

a busy cat]

Option 2: Use the verbatim environment

\begin{verbatim}
  your
  code
  example
\end{verbatim}