This is nearly a cross-post, as an almost identical post has been put in beginner forum. We don't like cross-posters.
Anyway. In what way "doesn't work"?
And another thing. This seems a very strange thing to be doing. Is it just a programming exercise? If not and it is for a real application,
you should probably take a simpler, more direct approach.