java中的二维阵列列表
问题描述:
因此,我正在处理的项目需要我有一维数组的二维阵列列表。但每次我试图在我的数据加载时间,我得到一个错误:java中的二维阵列列表
不能这样做,因为错误的输入 java.lang.IndexOutOfBoundsException这个opperation:指标:1,大小:0
的一些投入。我不知道我在哪里出错了。请帮助一下?
源代码:
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
}
答
这里:
machines.add(Integer.parseInt(fields[1])-1, column);
您没有指定大小的机器ArrayList的任何地方。 ArrayList会在您使用add的单参数版本时动态增长,因为它会添加到列表的末尾,但是在使用双参数版本时,ArrayList必须至少与您指定的索引一样长。由于您没有指定大小,并且您没有在任何地方使用单参数添加,所以ArrayList的大小为0,因此无论您提供哪个索引,它都会超出范围。您可以在创建ArrayList实例时指定大小,也可以在调用add之前使用ArrayList.ensureCapacity。
然后,你有同样的问题与get的行,试图对一个空的ArrayList使用双参数添加。
答
声明如下所示用于2D的ArrayList该ArrayList:
ArrayList<ArrayList<String>> my2DarrayList = new ArrayList<ArrayList<String>>();
现在在索引0处添加字符串的一个新的ArrayList:
my2DarrayList.add(new ArrayList<String>());
现在,作为新的ArrayList在索引0,所以输入您必须将如下所示的值添加到特定的ArrayList:
my2DarrayList.get(0).add("String is added here");
抛出异常在哪里?代码中可能存在各种各样的地方。 – tddmonkey 2010-12-21 20:36:58
this:machines.get(Integer.parseInt(fields [1]) - 1).add(Integer.parseInt(fields [2]) - 1,item); 是抛出异常的代码。 – 2010-12-21 20:44:53