0

My java code throws Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException?? The code looks like this. It is written in java. The IDE used is 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);


    }

}

My java code throws Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException?? And the error shows.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at week5.DecimalToHex.ConvertHexaToDec(DecimalToHex.java:27)
    at week5.DecimalToHex.main(DecimalToHex.java:12)
Xetree
  • 17
  • 9
  • For future reference [this post](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) pretty comprehensively covers `ArrayIndexOutOfBoundsException` and would help you in debugging this type of problem on your own. – Mihir Kekkar Apr 11 '20 at 06:13

1 Answers1

1
for(int i:eachChar)
{
  finalDeci=finalDeci+eachChar[i]*((int)Math.pow(10, i));
}

Here i has already value of eachChar[i], because you are using for-each loop instead of indexed for loop.

Look into For-Each Loop for more details.

Šimon Kocúrek
  • 1,591
  • 1
  • 12
  • 22