# Lstlisting format Java code

If I'm writing in Netbeans, I can easily format my code. How do I do that in lstlisting? I mean, if I am import it or copy it into my TeX document with the right spaces, everything is fine. But is there another method? Can TeX do it automatically?

• lstlisting of listing package can import a (raw) code files (ascii text) and keep the line breaking ogthis file. So where is the problem ? What do you men by "with the right spaces" ?
– Jhor
Jun 23 '18 at 14:57
• May be here is the answer tex.stackexchange.com/questions/169669/… Jun 23 '18 at 17:43

You can try the following

\usepackage{courier} %% Sets font for listing as Courier.
\usepackage{listings, xcolor}
\lstset{
tabsize = 4, %% set tab space width
showstringspaces = false, %% prevent space marking in strings, string is defined as the text that is generally printed directly to the console
numbers = left, %% display line numbers on the left
commentstyle = \color{green}, %% set comment color
keywordstyle = \color{blue}, %% set keyword color
stringstyle = \color{red}, %% set string color
rulecolor = \color{black}, %% set frame color to avoid being affected by text color
basicstyle = \small \ttfamily , %% set listing font and size
breaklines = true, %% enable line breaking
numberstyle = \tiny,
}

\begin{lstlisting}[language = Java , frame = trBL , firstnumber = last , escapeinside={(*@}{@*)}]
public class Factorial
{
public static void main(String[] args)
{   final int NUM_FACTS = 100;
for(int i = 0; i < NUM_FACTS; i++)
System.out.println( i + "! is " + factorial(i));
}

public static int factorial(int n)
{   int result = 1;
for(int i = 2; i <= n; i++) (*@\label{for}@*)
result *= i;
return result;
}
}
\end{lstlisting}

And you can reference line \ref{for} in the code!


Here is the output

• It is not an MWE. Jun 23 '18 at 18:02