在Switch语句中使用2个变量

时间:2015-02-27 12:42:24

标签: java 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语句可以识别小写字母或大写字母。

3 个答案:

答案 0 :(得分:8)

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

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");
}

答案 1 :(得分:1)

如果您在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");

    }

希望这会对你有所帮助。

答案 2 :(得分:1)

只需将字符串用作charr = sc.next().toLowerCase()charr = sc.next().toUpperCase(),然后使用您的情况。请说明您使用的是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原语类型来编译相同的