j.doe j.doe - 1 year ago 80
Java Question

Filling an array with arrays that contain doubles

I am working on a class assignment where we can only use arrays and no Collection classes to read a text file and fill an array with information from the text file. the file ArrayData.txt is the information bellow.
The file is formatted in this way:

3 //First line states how many sets are in the file
2 //Next line:there are x numbers in the set
10.22 567.98 //Next Line states the doubles that are in the set
//The pattern continues from there
1 // x numbers in the next set
20.55 // Double in the set
20.55 2.34 100.97

My issue is filling the initial array with an array, then filling the second array with the doubles.

Essentially, I want it to look like this:

initArray[0]=> smallArray[2]={10.22,5.67.98}
initArray[1]=> smallArray[1]={20.55}
initArray[2]=> smallArray[3]={20.55,2.34,100.97}

Here is what I have so far:

public static double[] largeArray;
public static double[] insideArray;
public static void main(String[] args) {

String fileInputName = "ArrayData.txt";
Scanner sc = null;
try {
sc = new Scanner(new BufferedReader(new FileReader(fileInputName)));
while (sc.hasNextLine()) {

int i = sc.nextInt();
largeArray= new double[i];
for(int x=0; x<i;x++)
int z = sc.nextInt();

insideArray= new double[z];
for(int y=0; y<z; y++)
catch (FileNotFoundException e) {
finally {
if (sc != null)

First off, does this logic even make sense? Secondly, I keep getting an array out of bounds error, so I know something is right, I'm just not sure where.

Answer Source

Remove the while. You want the body to execute only once. Line breaks at the end of the file may cause it to run again and then there will be no nextInt(). If you want to support empty files, make it an if.

Secondly, insideArray[z] = ... should be insideArray[y] = ...

Finally, largeArray should be an array of arrays double[][] (a so called jagged array) and you want to assign insideArray to the according place after filling it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download