WÜRZBURG, Germany — Over the weekend, an Afghan teenager who had arrived as a refugee last year told confidants in Germany that he had lost a close friend in Afghanistan, but who had been killed, and how and where, remained unclear.

The news seemed to unhinge the 17-year-old, who had been specially selected for foster care because he seemed to be adjusting well to his new life in Germany. His foster family noticed that the normally quiet young man appeared agitated and that he spent a lot of time on his phone.

But when he told them on Monday that he was going out for a bike ride and might be gone for a while, they had no inkling that he had left armed with an ax and a knife, determined to carry out a brutal attack in the name of the Islamic State.

Hours later, five people were hospitalized — two of them critically — after the teenager slashed them about the head and torso on a passenger train, shouting “Allahu akbar,” or God is great. The Afghan teenager, whom officials did not identify, then fled and attacked a woman walking her dog before he was cornered and killed by the German police.