Read the serial input basics tutorial. Those are proven methods for reading serial input.
It is preferred that you post the whole code. It may be OK in this instance, but often there is information missing when snippets are posted.
Good work posting in code tags on your first post. Not many new members bother reading the guide lines. Thank you and welcome.