I am trying to set up an environment for making exercises with corresponding answers for students.
Idea
I would like to be able to write the text for an exercise in an environment, and directly after write the answer (preferably in another environment). The exercise should show up where it is written, but the answers should remain hidden until a command, e.g. \listofanswers
, is issued. This command would then output the answer to every question at the very place the command is issued (just like inserting e.g. \listoffigures
or a bibliography). The answers should appear with the same numbering as the exercises they provide answers to. In this way, I could collect every answer and only show them at the end of the document instead of right after their corresponding exercise.
Current status
This is what I have been able to hack together so far:
\documentclass{scrartcl}
% Exercise environment:
\newcounter{exercise}
\newenvironment{ex}[1]{\refstepcounter{exercise}\par\medskip\noindent%
\textbf{Exercise~\theexercise\ #1\quad} \rmfamily}{\medskip}
% Basic answer environment that should take care of formatting:
\newenvironment{ansenv}{\par\medskip\noindent%
\textbf{Answer to exercise~\theexercise\quad} \rmfamily}{\medskip}
% Create a new answer environment that will store the answer for outputting later:
\usepackage{etoolbox}
\usepackage{environ}
\newcommand{\listofanswers}{}
\NewEnviron{answer}{
\xappto{\listofanswers}{
\begin{ansenv} \BODY \end{ansenv}
}
}
\begin{document}
\section{Exercises}
\begin{ex}{Exercise title 1}
This is the first exercise.
\end{ex}
\begin{answer}
This is the answer to the first exercise, and should only show up when and where \verb!\listofanswers! is used.
\end{answer}
\begin{ex}{Exercise title 2}
This is the second exercise.
\end{ex}
\begin{answer}
This is the answer to the second exercise, and should only show up when and where \verb!\listofanswers! is used.
\end{answer}
This is something that is neither an exercise nor an answer.
\section{Answers}
% Output all answers right here at the very end of the document:
\listofanswers
\end{document}
Expected result
I would like to see something like the below:
Actual result
Compiling gives me the following error:
! Argument of \@firstoftwo has an extra }.
<inserted text>
\par
l.32 \end{answer}
Can someone help me track down the bug or know of a better way to accomplish my exercise and answer environments?
exsheets
seem to do exactly what I want -- thank you very much! :)