Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   Insertig An Element (http://www.programmingforums.org/showthread.php?t=1508)

xavier Dec 12th, 2004 5:30 AM

c1="1234"
c2="123456" those are both char arrays.
I want to make them eqwals in elngth :

c1="001234"
c2="123456"

Like that, inserting '0' in the first array......Now, i dont know wich array is shortest. I've tried it like this:
int N=c1.length;
int M=c2.length;

:

while(N!=M){
 if(N<M){
        for(int j=N;j>=1;j--)
        c1[j]=c1[j-1];
        c1[0]='0';
            N++;
 }
 if(N>M){
        for(int k=M;k>=1;k--)
        c2[k]=c2[k-1];
        c2[0]='0';
        M++;
 }
        }


It gives IndexOutOfBounds at: c1[j]=c1[j-1]; or c2[k]=c2[k-1]
I don't realy undersand y.

Also i don't want to copy the shortest array into a new one and inserting the zeros there ...
It's a simple problem .. but i just can't find an answere.
HELP :(

andersRson Dec 12th, 2004 6:05 AM

The reason is that you are accessing the array index N or M, which doesn't exist. There are N and M elements in the arrays, indexed from 0 to N - 1 and M - 1. So there is no element at c1[N] and c2[M], the arrays end at c1[N - 1] and c2[M - 1].
You cannot just index out of the array and expect it to grow magically, the size is fixed at the arrays creation. You will have to create new arrays and copy the contents of the old ones into the new ones.

xavier Dec 12th, 2004 6:25 AM

Ok, thanks for the info :)

ZenMasterJG Dec 12th, 2004 3:39 PM

If you want it to grow magically, use a Vector. (Or an arraylist, i think, im not hip to a bunch of the new Java 5 weirdness)


All times are GMT -5. The time now is 3:59 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC