Where is my fault?
loop() is supposed to define what has to be done at one moment in time.
After reading the input, deciding, eventually doing a different output than before, it should return, just to be called again.
So replace your while by an else if ( ) ... and eventually add more decision cases