0

I have been working with a java, and wanted to Store the data in 2-d Array 12x2, Below shown is the way to Store the data: enter image description here

Below is the code for that i built,but unfortunately i am getting Exception

java.lang.ArrayIndexOutOfBoundsException: 4

String[][] netswtich=new String[12][2];

for(int i =0;i<4;i++)
              {
                  for(int j=4;j>0;j--)
                  {
                        if(i==j) 
                        {
                            continue;
                        }
                        netswtich[k][0]=ranArray[i];
                        netswtich[k][1]=ranArray[j];
                        k++;
                  }
              }
7
  • I assume the problem is with ranArray[...] You do not show what is inside ranArray and also not what the start value of k is... Commented Mar 18, 2013 at 8:14
  • It will cause exception because in your array you have used size of array to 12 i.e. i will goo to 0-11 but for 2nd dimension you have used 2 i.e. j will go to 0-1 but you are comparing j==4 Commented Mar 18, 2013 at 8:14
  • and how did you initialize ranArray? you might get an exception on ranArray[4] Commented Mar 18, 2013 at 8:14
  • K=0; and ranArray consist of 5 strings.. Commented Mar 18, 2013 at 8:16
  • String[] ranArray = new String[4] Commented Mar 18, 2013 at 8:17

2 Answers 2

4

My guess you are getting array out of bounds on ranArray if the size of the vector is 4 you should start j from 3 to 0 for(int j=3;j>=0;j--)

Sign up to request clarification or add additional context in comments.

Comments

0

This means that you want to access an array element which isnt there, e.g. you want to access ranArray[4] while ranArray only holds 4 (or less elements), which means that 3 is the last usable array element.

2 Comments

but why can't it hold 5 elements..i mean starting from 0 1 2 3 4
If you define it as "String[] ranArray=new String[4];" that means that it can hold four elements. But since we start counting at 0 and not 1, this means that 3 is actually the fourth (and as such, the last) element: ranArray[0] ranArray[1] ranArray[2] ranArray[3] are the four usable elements. If you need more, just change the 4 to a 5 (or whatever else you need) at the definition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.