Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Capturing "Enter Key" or "Blank" in Switch Statement  RSS feed

 
Ken Huskerson
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am looking for a way to capture the enter key for user input used in a switch statement.

The problem is when a user doesn't entere a valid value and just presses the enter key.

I though it might be capture as:

if(action = null || action = " ")

but neither are working.

Is there some kind of escape character I should be checking for?

Thanks in advance!

kh
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ken ,

Welcome to JavaRanch!

First, if you're reading lines from standard input using a BufferedReader or something similar, then if the user just presses Enter, you'll get an empty string, "" (no space between the quotes.)

Second, to compare String objects, you need to use the equals() method, and not the "==" operator. The former compares contents of Strings; the latter tells you if the two strings are the same physical object in memory.

So you're looking for something like

if (action == null || action.equals(""))
 
Ken Huskerson
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm embarrassed. I should have know that. Thank you for the quick response.



kh
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No need to feel embarrassed. It's for questions like these that the Beginners forum exists.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!