Java:Char to Int转换的重点是什么,然后将Int与Char进行比较?为什么这有效?

时间:2016-04-22 14:23:46

标签: java char int switch-statement

我在读Java书。有一个我没有得到的代码。如果我们需要与CHAR进行比较,为什么我们将结果保存在INT中呢?为什么这个工作正常?

˜

1 个答案:

答案 0 :(得分:0)

在切换中使用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,甚至可以转换为您在切换案例中使用的SELECT Format(DatePart("m",months.month_start),"00") & "/" & Year(months.month_start) AS [Month/Year], (Select sales_rep.rep_name FROM SALES_REP WHERE SALES_REP.rep_Name = "Eileen") AS [Sales Person], (select Round(Nz(Sum(sales_receipt.SELLING_PRICE * sales_receipt.quantity),0) ,2) FROM SALES_RECEIPT INNER JOIN SALES_REP ON SALES_REP.REP_ID = SALES_RECEIPT.REP_ID WHERE SALES_RECEIPT.[SALE_DATE] between months.month_start and months.month_end and SALES_REP.rep_Name = "Eileen") AS [Total Sales], (SELECT Round((Sum(((Nz(SALES_RECEIPT.SELLING_PRICE,0)*Nz(sales_receipt.quantity,0))*(Nz(sales_receipt.commission_percent,100)*0.001)))),2) FROM SALES_RECEIPT INNER JOIN SALES_REP ON SALES_REP.REP_ID = SALES_RECEIPT.REP_ID WHERE SALES_RECEIPT.[SALE_DATE] between months.month_start and months.month_end and SALES_REP.rep_Name = "Eileen") AS [Gross Commission] FROM (SELECT DateSerial(Year(sale_date), Month(sale_date), 1) AS month_start, DateAdd("d", -1, DateSerial(Year(sale_date), Month(sale_date) + 1, 1)) AS month_end FROM SALES_RECEIPT WHERE sale_date between #1/1/2015# And #12/31/2050# GROUP BY Year(sale_date), Month(sale_date)) AS months; 。因此,关于您是使用char还是int literal形式,这只是一个偏好/便利/可读性的问题。