【问题标题】:My java code throws Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException? [duplicate]我的 java 代码在线程“main”java.lang.ArrayIndexOutOfBoundsException 中抛出异常? [复制]
【发布时间】:2020-04-11 06:04:44
【问题描述】:

我的 java 代码在线程“main”java.lang.ArrayIndexOutOfBoundsException 中抛出异常?? 代码看起来像这样。它是用java编写的。使用的 IDE 是 Eclipse。

package week5;

import java.util.*;
import java.lang.Math;

public class DecimalToHex {

    public static void main(String[] args) {
        Scanner sn=new Scanner(System.in);
        System.out.println("--Enter Hexadecimal Number--");
        String hex=sn.next();
        ConvertHexaToDec(hex.toUpperCase());
        sn.close();
    }

    public static void ConvertHexaToDec(String hex)
    {
        String hexChar="0123456789ABCDEF";
        int[] eachChar=new int[hex.length()];
        int finalDeci=0;
        for(int i=0;i<hex.length();i++)
        {
            eachChar[i]=hexChar.indexOf(hex.charAt(i));
        }
        for(int i:eachChar)
        {
            finalDeci=finalDeci+eachChar[i]*((int)Math.pow(10, i));
        }
        System.out.println("Decimal Value Is "+finalDeci);


    }

}

我的 java 代码在线程“main”java.lang.ArrayIndexOutOfBoundsException 中抛出异常?? 并显示错误。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at week5.DecimalToHex.ConvertHexaToDec(DecimalToHex.java:27)
    at week5.DecimalToHex.main(DecimalToHex.java:12)

【问题讨论】:

  • 供将来参考 this post 相当全面地涵盖了 ArrayIndexOutOfBoundsException 并将帮助您自行调试此类问题。

标签: java arrays math console-application


【解决方案1】:
for(int i:eachChar)
{
  finalDeci=finalDeci+eachChar[i]*((int)Math.pow(10, i));
}

这里i 的值已经是eachChar[i],因为您使用的是for-each 循环而不是indexed for 循环。

查看For-Each Loop 了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2020-11-05
    相关资源
    最近更新 更多