# A problem with counters

While trying to answer a question I came upon a problem with counters and I need some help. The idea is to collect answers to some numbered exercises, so the collected answers can be all typeset at some later point in the document; my approach was to use the collect package to, well, collect the answers:

\documentclass{scrartcl}
\usepackage{collect}

\makeatletter
{\par}%
{}%
{}%
}
{\@nameuse{endcollect}}
\makeatother

\newcounter{exercise}
\newenvironment{ex}
{\refstepcounter{exercise}\par\noindent This is exercise~\theexercise}
{\par}

\begin{document}

\begin{ex}
\end{ex}
This is the answer to exercise 1 but it is numbered 3.

\begin{ex}
\end{ex}
This is the answer to exercise 2 but it is numbered 3.

\begin{ex}
\end{ex}
This is the answer to exercise 3 and it is numbered 3.

\end{document}


However, as it was expected, using this approach, all the answers receive the number corresponding to the last value of the exercise counter and not the number associated to their corresponding exercise (see the image). How can this be solved?

You have to expand \theexercise before doing the write:

\documentclass{scrartcl}
\usepackage{collect}

\newcommand\mycollect[1]{%
{\par}
{}{}%
}

{\begingroup\edef\x{\endgroup\noexpand\mycollect{\theexercise}}\x}
{\endcollect}

\newcounter{exercise}
\newenvironment{ex}
{\refstepcounter{exercise}\par\noindent This is exercise~\theexercise}
{\par}

\begin{document}

\begin{ex}
\end{ex}
This is the answer to exercise 1 but it is numbered 3.

\begin{ex}
\end{ex}
This is the answer to exercise 2 but it is numbered 3.

\begin{ex}
\end{ex}