-1

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

while(!sc.hasNext("quit")){
   ...}

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

  • 2
    Yes. [Read the Javadocs](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html). The `Scanner.hasNext(String)` is a pattern. You can also use the `Scanner.hasNext(Pattern)` if needed. – KevinO Apr 27 '16 at 23:19

3 Answers3

1

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

Community
  • 1
  • 1
KevinO
  • 4,303
  • 4
  • 27
  • 36
0

One way around this is by taking the user input and automatically sending all chars in the sting to upper or lower case and then checking that. Then it wouldn't matter what the user put in.

String str1 = new String(); 
str1 = scanner.nextLine();
str1.toUpperCase();
while(str1.equals("QUIT")){....}
0

Maybe you can try like this:

String input = sc.next();
while(!input.equalsIgnoreCase("quit"){
 ...
}