2 dimensional arraylists in java
- by Chris Maness
So here's the deal I'm working on a project that requires me to have a 2 dimensional arraylist of 1 dimensional arrays. But every time I try to load in my data I get an error:
Can't do this opperation because of bad input
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
On some of the inputs. I've got no idea where I'm going wrong on this one. A little help please?
Source Code:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.InputStream;
public class Facebull
{
public static void main (String[] args) {
if(args.length != 0){
load(args[0]);
}
else{
load("testFile");
}
}
public static void load(String fname) {
int costOfMach = 0;
ArrayList <Integer> finalMach = new ArrayList<Integer>();
ArrayList <ArrayList<int[]>>machines = new ArrayList<ArrayList<int[]>>();
Scanner inputFile = null;
File f = new File(fname);
if (f.exists ())
{
try
{
inputFile = new Scanner (f);
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null,"Can't find the file\n" + e);
}
int i = 0;
while (inputFile.hasNext ( ))
{
String str = inputFile.nextLine ( );
String [ ] fields = str.split ("[\t ]");
System.out.println(str);
if (!(fields[0].isEmpty() || fields[0].equals (""))){
fields[0] = fields[0].substring(1);
fields[1] = fields[1].substring(1);
fields[2] = fields[2].substring(1);
try
{
//data to be inputed is 0 and 3 location of data is 1 and 2
int[] item = new int[2];
item[1] = Integer.parseInt(fields[0]);
item[0] = Integer.parseInt(fields[3]);
if(machines.size() < Integer.parseInt(fields[1])){
ArrayList<int[]> column = new ArrayList<int[]>();
machines.add (Integer.parseInt(fields[1])-1, column);
System.out.println("we're in the if");
}
machines.get(Integer.parseInt(fields[1])-1).add(Integer.parseInt(fields[2])-1, item);
}
//catches any exception
catch (Exception e)
{
System.out.println("Can't do this opperation because of bad input \n" + e);
}
}
}
inputFile.close ( );
}
System.out.print(machines);
}//end load
}