valik
valik

Reputation: 2094

I getting ArrayIndexOutOfBoundsException

I am trying to convert a String array to int array and then compare elements if they are equal so far i am getting an error, first this is the method that converts string array to to int array

private static int[] convertStringArrayToIntArray(String[] strVals) {
        int[] intVals = new int[strVals.length];
        for (int i=0; i < strVals.length; i++) {
            intVals[i] = Integer.parseInt(strVals[i]);
        }
        Arrays.sort(intVals);
        return intVals;
    }

Now the method below is where i am getting the exception

public static String ScaleBalancingCorrect(String[] strArr) {
        int[] startWeights = convertStringArrayToIntArray(strArr[0].replaceAll("[^0-9,]", "").split(","));
        int[] availWeights = convertStringArrayToIntArray(("0," + strArr[1]).replaceAll("[^0-9,]", "").split(","));

        if (startWeights[0] != startWeights[1]) { //I get exception here
            for (int i = 0; i < availWeights.length; i++) {
       // omited code for brevity  

this is what i was running when i got the exception

public static void main(String [] arg) {
        String [] arr = {"34","1277"};

      ScaleBalancingCorrect(arr);
     }

Upvotes: 1

Views: 25

Answers (1)

user3738870
user3738870

Reputation: 1632

Maybe it's just a typo and you wanted to write if (startWeights[0] != availWeights[1]). availWeights will always have at least two elements, since you add 0 as a first element before the supplied other element(s). startWeights, however, as in your example, may only have one element (in your example, it's 34).

Upvotes: 1

Related Questions