【问题标题】:converting character to array index将字符转换为数组索引
【发布时间】:2014-12-23 02:53:47
【问题描述】:

我正在尝试通过从字符串中读取数组索引来访问字符数组。

public class HelloWorld {

    public static void main(String[] args) {
        //             0123456789
        char[] code = {'A', 'B','C','D','E','F','G','H','I','J'};
        String orig = "0123456789";
        for ( int i=0; i <10; i++) {
            System.out.print(code[orig.charAt(i)]);
        }
    }

}

我希望得到ABCDEFGHIJ 的输出,但我得到了一个运行时错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 48
    at HelloWorld.main(HelloWorld.java:9)

【问题讨论】:

  • 您是否尝试在循环中添加断点以查看代码实际在做什么?

标签: java arrays type-conversion


【解决方案1】:

这是因为 orig.charAt(i) 返回一个 ascii 字符。所以“0”实际上是数字 48。您可以通过以下方式轻松解决此问题:

code[orig.charAt(i) - 48];

【讨论】:

    【解决方案2】:

    当您使用orig.charAt(i) 作为索引时,char 值将转换为int。每个字符都有一个数值。例如,'0' 是 48。您可以减去遇到的最小字符值以获得正确范围内的索引:

    System.out.print(code[orig.charAt(i) - '0']);
    

    【讨论】:

      【解决方案3】:

      只需对字符串的长度进行索引并在该索引处获取代码数组的字符... charAt 将为您提供文字 int 值,这显然不是您想要的。

      public static void main(String[] args) {
              //  0123456789
              char[] code = {'A', 'B','C','D','E','F','G','H','I','J'};
              String orig = "0123456789";
              for ( int i=0; i < orig.length(); i++) {
                  System.out.print( code[i] );
              }
          }
      

      【讨论】:

        【解决方案4】:

        由于数组索引是 int,它会自动转换为 int。
        但 char '0' 的 int 值为 48,因此出现消息“ArrayIndexOutOfBoundsException”。
        下面的代码应该做到这一点

        System.out.print(code[orig.charAt(i)-48]);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-01-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-02
          • 1970-01-01
          相关资源
          最近更新 更多