Numbers and programming code

This happens when I use programming code and enumeration, how can I add a gap between the numbering and the line numbers of the code. enter image description here

I’m using this in LaTeX Preamble:

\usepackage{listings}
\lstset{language=java,numbers=left,tabsize=2,showstringspaces=false,showspaces=false}

Solutions Collecting From Web of "Numbers and programming code"

Besides addin xleftmargin=<size> to shift the listings over, you also need resetmargins=true which resets the indention from list environments like enumerate or itemize.

The frame here is from the geometry package to show the alignment with the margins.

enter image description here

Code:

Commenting out the resetmargins=true below will illustrate the problem.

\documentclass{article}
\usepackage[showframe]{geometry}
\usepackage{listings}

\lstset{
    language=java,
    numbers=left,
    tabsize=2,
    showstringspaces=false,
    showspaces=false,
    numberstyle=\tiny,
    xleftmargin=4em,
    resetmargins=true,
}


\begin{document}
\begin{enumerate}
\item
\begin{lstlisting}
 public int nextInt(int n) {
     if (n<=0)
     return val;
 }
\end{lstlisting}
%
\item abcd
%
\item
\begin{lstlisting}
 public int nextInt(int n) {
     if (n<=0)
     return val;
 }
\end{lstlisting}
\end{enumerate}
\end{document}