Janek Sławiński Janek Sławiński - 8 months ago 27
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 ?


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