File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Array problem. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Array problem." Watch "Array problem." New topic
Author

Array problem.

Mark Hughes
Ranch Hand

Joined: Jul 14, 2006
Posts: 146
Hey guys,

Right something here i dont quite understand i wonder can some one shed some light on it for me please. Right so i import csv file with 2 lines into app and use an array to split commas as follows;

code:
for (int i = 0; i < textfile.length; i++) { //textfile contains .csv file
piece = textfile[i].split("[,]"); //piece is string array
for (int j = 0; j < piece.length; j++)
System.out.print(piece[j] + "\t");
System.out.print("\n");
}

Now this prints the following;
apple1.53
pear1.12
which is what i expect, but then i try and place an attribute of the array at one specific memory slot into a single variable, from what i understand the array should be 0,1,2,3,4,5; with 0 being apple, 1 being "1.5" and so on but when i do this;

fruit = piece[0];

fruit being a string, i thought this should put apple into fruit but instead it puts pear in to fruit, and app throws index out of boubds exception if i go above memory slot 2, eg fruit = piece[3];
Can some please explain to me where im gone wrong in my thinking, thanks
Mark
Fahd Shariff
Ranch Hand

Joined: Nov 22, 2002
Posts: 38
This is because the piece array gets "overwritten" each time the split method is called i.e.

When i = 0
piece contains [apple, 1.5, 3]

Next iteration, i=1
piece now contains [pear, 1.1, 2] NOT [apple, 1.5, 3, pear, 1.1, 2]

Therefore, piece[0] = pear, NOT apple! You are not adding to a single array, but creating a new one each time.

Hope this helps,

--
Fahd Shariff


Fahd Shariff<br />"Let the code do the talking"
Mark Hughes
Ranch Hand

Joined: Jul 14, 2006
Posts: 146
Yea that makes sense allright i must say, i thought declaring and initialising the array and variables outside the loop would let me just build the array up without over writing the array, could you suggest a way around this small prob that i could work on, thanks
Fahd Shariff
Ranch Hand

Joined: Nov 22, 2002
Posts: 38
The simplest solution would be to add each piece element to a list:


Now you can say
Mark Hughes
Ranch Hand

Joined: Jul 14, 2006
Posts: 146
Thats brillant,
Why did'nt i think of that, i was kinda on right track ha ha,
sure the learning continues!

Thanks very much
Mark
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array problem.