Anne Bailly
Anne Bailly

Reputation: 411

Invoking ignore case in switch statements

In the below code containing the switch statements, is it possible to incorporate the equalsIgnoreCase method, i.e., user gets grade message whether or not a or A is entered, etc. etc.?

I managed to get the right result by using "convert user input to upper case" method, but I was curious whether the ignoreCase method can be used here. I tried to do it, but it does not seem to work in any way, possibly because ignoreCase is a Boolean which returns true/false result, not a message. I tried researching this, but all online results suggest using toUpperCase method, something I already tried and worked.

  Scanner scan = new Scanner(System.in);
  System.out.println("Please enter grade.");
  String gradeLetter = scan.next();
  String message = "A";
  switch (gradeLetter) {
  case "A":
      message = "Excellent!";
      break;
  case "B":
      message = "Good job.";
      break;
  case "C":
      message = "You passed.";
      break;
  case "D":
      message = "You can do better.";
      break;
  case "F":
      message = "You failed.";
      break;
      default: message = gradeLetter + " is invalid.";
  }

    System.out.println(message);

Upvotes: 1

Views: 269

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

You could switch (gradeLetter.toUpperCase()) but this looks like a better use case for Map<String, String> to me. Something like

Scanner scan = new Scanner(System.in);

Map<String, String> map = new HashMap<>();
map.put("A", "Excellent!");
map.put("B", "Good job.");
map.put("C", "You passed");
map.put("D", "You can do better.");
map.put("F", "You failed.");

// ... No Loop?
System.out.println("Please enter grade.");
String gradeLetter = scan.next();

System.out.println(map.getOrDefault(gradeLetter.toUpperCase(), 
        String.format("%s is invalid.", gradeLetter)));

Upvotes: 3

nanofarad
nanofarad

Reputation: 41281

As you already mentioned, you can switch on gradeLetter.toUpperCase().

You can also use fall-through, where multiple case labels jump to the same block of code:

switch (gradeLetter) {
  case "A":
  case "a":
      message = "Excellent!";
      break;
  case "B":
  case "b":
      message = "Good job.";
      break;
  /* etc */

Consider, for example, "a" and "A". There is no break statement after case "A":, so execution continues straight into the case "a": block.

Upvotes: 2

Related Questions