在 Switch 语句中使用 2 个变量

Using 2 variables in Switch statement

import java.util.Scanner;

class Test {
  public static void main(String args[]) {
    String charr;

    try{    
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the Value ");

      charr = sc.next();
      switch (charr +"|"+ charr) {
        case "a|A" : System.out.println("a | A"); break;
        case "b|B" : System.out.println("b | B"); break;
        case "c|C" : System.out.println("c | C"); break;
        case "d|D" : System.out.println("d | D"); break;
        default:  System.out.println("You are doing it wrong");
      }
    } catch(java.util.InputMismatchException e) {
      System.out.println("Exception thrown :" + e);
    }

    System.out.println("Out of Block");
  }
}

大家好,我的程序是只输入1个字符,但是我的switch语句可以识别小写字母或大写字母。

您可以使用多个大小写来识别大小写字母:

switch (charr) {
    case "a": case "A" : System.out.println("a | A"); break;
    case "b": case "B" : System.out.println("b | B"); break;
    case "c": case "C" : System.out.println("c | C"); break;
    case "d": case "D" : System.out.println("d | D"); break;
    default:  System.out.println("You are doing it wrong");
}

然而,更简单的替代方法是在检查之前转换为小写或大写:

switch (charr.toLowerCase()) {
    case "a": System.out.println("a | A"); break;
    case "b": System.out.println("b | B"); break;
    case "c": System.out.println("c | C"); break;
    case "d": System.out.println("d | D"); break;
    default:  System.out.println("You are doing it wrong");
}

如果您在 java 7 及更高版本中执行

尝试将字母转换为大写,如下所示

switch (charr.toUpperCase())
    {
    case "A" : System.out.println("a | A"); break;
    case "B" : System.out.println("b | B"); break;
    case "C" : System.out.println("c | C"); break;
    case "D" : System.out.println("d | D"); break;
    default:  System.out.println("You are doing it wrong");

    }

希望对您有所帮助。

只需将字符串用作 charr = sc.next().toLowerCase()charr = sc.next().toUpperCase() 而不是使用 case.Let 表示您使用的 toLowercase(); 而不是

 switch (charr) {
case "a": System.out.println("a | A"); break;
case "b": System.out.println("a | A"); break;
case "c": System.out.println("a | A"); break;
case "d": System.out.println("a | A"); break;
default:  System.out.println("You are doing it wrong");
}

注意:这将在 JAVA 7 中编译,否则使用 char 原始类型编译相同的