Take this line out
if(key) // Check for a valid key.
The line above it has already read the key in if one was pressed.