Janek Sławiński Janek Sławiński - 2 years ago 89
Java Question

Can one make hasNext() case insensitive?

My main menu is inside the while loop that checks if user wants to quit.


Can I make hasNext() case insensitive, so user can type any variation of cases in word 'quit', like QuIt or quIt ?

Answer Source

I believe the String pattern "^(?i)quit$" passed to the sc.hasNext(String) will work.

final String QUIT_PAT = "^(?i)quit$";
while (! sc.hasNext(QUIT_PAT)) {

I don't have an easy Scanner set up to test, but the regex should work.

However, I would suggest read this answer that suggests embedding the check when using stdin might not be the best approach.

Example Test Results of the regex: enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download