Java:Char到Int转换然后比较Int到Char是什么意思?为什么这个工作?

问题描述:

我正在阅读Java-book。有一个我没有得到的代码。为什么我们要将结果保存在INT中,如果我们需要与CHAR进行比较呢?为什么这个工作正常?Java:Char到Int转换然后比较Int到Char是什么意思?为什么这个工作?

public static **char** getChar() throws IOException 
    { 
    String s = getString(); 
    return s.charAt(0); 
    } 
**int** choice = getChar(); 

switch(**choice**) 
    { 
      case **'s'**: {} 
      case 'r': {} 
      case 'n': {} 
      case 'g': {}     
      case 'b': {}     
      case 'a': {}     
      case 'd': {}     
      default: {} 
    } 
+3

堆栈溢出不是您的Java书的作者。 – khelwood

+1

可能这个例子是从C中提取的,在switch语句中使用的表达式必须具有整型或枚举类型。在Java中没有理由这么做。 – azurefrog

+0

'char'是一个完整的类型,扩大转换是合法的。 –

有一个在开关使用charint文字之间没有差异:

public static void withCharLiteral() { 
    int choice = getChar(); 
    switch (choice) { 
    case 's': 
     break; 
    } 
} 

编译为:

public static void withCharLiteral(); 
    Code: 
     0: invokestatic #2     // Method getChar:()C 
     3: istore_0 
     4: iload_0 
     5: lookupswitch { // 1 
        115: 24 
       default: 24 
      } 
     24: return 

VS与int字面:

public static void withIntLiteral() { 
    int choice = getChar(); 
    switch (choice) { 
    case 115: 
     break; 
    } 
} 

编译为:

public static void withIntLiteral(); 
    Code: 
     0: invokestatic #2     // Method getChar:()C 
     3: istore_0 
     4: iload_0 
     5: lookupswitch { // 1 
        115: 24 
       default: 24 
      } 
     24: return 

所有char可以转换为int,即使你在开关的情况下使用的。因此,这只是关于您是使用char或int字面量形式的首选/便利/可读性的问题。