'Array Problems java.lang.ArrayIndexOutOfBoundsException: 9

I am trying to write a class that takes a phone number that the user inputs as a string, then stores each digit in an array. I converted the string to a long using Long.parseLong. Here is the function that is supposed to store each individual digit in an array.

public void storetoarray()
        //Turn the strings to longs
        //A loop chops of the last digit and stores in an array
{
    phonelong = Long.parseLong(initialphone);
    phonetemp1 = phonelong;
    for (int i = phonelength; i>=0; i--)
    {
        phonearray[i-1] = phonetemp1%10;
        phonetemp2 = phonetemp1 - phonetemp1%10;
        phonetemp1 = phonetemp2/10;
        System.out.print("Phone temp 2" + phonetemp2 + phonetemp1);
    }
}

The logic of that loop is to find the last digit of the phone number using a %10, then subtract that number from the original phone number. That new difference is then set to be phonetemp1/10.

Example 4158884532%10 = 2. That is stored in phonearray[9]. Then phonetemp2 is subtracted giving us 4158884530. Divide that by 10 and you get 415888453. Should be ready to store the next digit.

What is going wrong? Thanks for the help!



Solution 1:[1]

Your phonearray does not have enough space: you are accessing index 9, but phonearray has fewer than ten elements.

You need to allocate the array like this:

phonearray = new int[10];

Once you fix this problem, change the loop to avoid accessing index -1 (that's what is going to happen when i reaches zero).

Finally, there is no need to subtract phonetemp1%10 from phonetemp1: integer division drops the fraction, so you could do this:

phonearray[i-1] = phonetemp1%10;
phonetemp1 /= 10;

Solution 2:[2]

If you have initialized the array correctly with the size same as the length of the initialPhone, you should not see this exception. Your code would rather produce ArrayIndexOutOfBoundException: -1 Rewrote your code a bit, and works as expected:

import java.util.Arrays;

public class TestMain {

  public static void main(String[] args) {

    String initialPhone = "4158884532";
    int phoneLength = initialPhone.length();
    long[] phoneArray = new long[phoneLength];

    Long phoneNum = Long.parseLong(initialPhone);
    Long phonetemp1 = phoneNum;
    for (int i = phoneLength; i > 0; i--) {
      phoneArray[i - 1] = phonetemp1 % 10;
      Long phonetemp2 = phonetemp1 - phonetemp1 % 10;
      phonetemp1 = phonetemp2 / 10;
      System.out.println("Phone temp 2 --> " + phonetemp2 + phonetemp1);
    }
    System.out.println(Arrays.toString(phoneArray));
  }
}

Enjoy!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergey Kalinichenko
Solution 2 moonlighter