在将元素插入二维数组时获取ArrayIndexOutOfBoundException
..我不知道问题出在哪里..
我尝试了很多,但无法理解为什么这会给出异常。这是我的代码..提前谢谢..
public class TruthTableAutoMateClass extends JPanel implements ActionListener
{
static int size;
private int i = 0;
static JButton btnOk = new JButton();
String[][] array= new String[size][];
private double[][] dim = { {0.50, 0.50}, {0.25, 0.20, 0.20, 0.20, TableLayout.FILL}};
public static void main(String args[])
{
TruthTableAutoMateClass auto = new TruthTableAutoMateClass();
checkAdding(auto);
btnOk.addActionListener(auto);
}
private static String[] prepareArray()
{
String[] arr = new String[2];
if (size == 16)
{
String text1 = field1.getText();
String text2 = field2.getText();
String text3 = field3.getText();
String text4 = field4.getText();
String firstArray = new StringBuilder().append(text1).append("|").append(text3).append("|").append(text3).append("|").append(text4).toString();
arr[0] = firstArray;
arr[1] = ledValue1.getText();
}
else if (size == 9)
{
}
else if (size == 4)
{
}
return arr;
}
private static void checkAdding(TruthTableAutoMateClass auto1)
{
TruthTableAutoMateClass auto = auto1;
String answer = JOptionPane.showInputDialog("How many values are there 4 or 3 " + "if 4 yes else press no");
if (answer.equalsIgnoreCase("yes"))
{
size = 4 * 4;
auto.add(lbl1, "0,0");
auto.add(lbl2, "0,1");
auto.add(lbl3, "0,2");
auto.add(lbl4, "0,3");
auto.add(field1, "1,0");
auto.add(field2, "1,1");
auto.add(field3, "1,2");
auto.add(field4, "1,3");
auto.add(ledValue1, "1,4");
/*auto.add(ledValue2);
auto.add(ledValue3);
auto.add(ledValue4);*/
auto.add(btnOk, "0,4");
}
else
{
size = 3 * 3;
String answer2 = JOptionPane.showInputDialog("Again enter yes or no" + "3 for yes , 2 for no");
if (answer2.equalsIgnoreCase("yes"))
{
auto.add(lbl1, "0,0");
auto.add(lbl2, "0,1");
auto.add(lbl3, "0,2");
auto.add(field1, "1,0");
auto.add(field2, "1,1");
auto.add(field3, "1,2");
auto.add(ledValue1, "1,4");
/* auto.add(ledValue2);
auto.add(ledValue3);*/
auto.add(btnOk, "0,4");
}
else
{
size = 2 * 2;
auto.add(lbl1, "0,0");
auto.add(lbl2, "0,1");
auto.add(field1, "1,0");
auto.add(field2, "1,1");
auto.add(ledValue1, "1,4");
/* auto.add(ledValue2);*/
auto.add(btnOk, "0,4");
}
}
}
@Override
public void actionPerformed(ActionEvent e)
{
array[i] = prepareArray();
i++;
System.out.println(Arrays.toString(array));
}}
答案 0 :(得分:1)
在main()
方法中,您正在创建TruthTableAutoMateClass
的实例。当这个创建时,size = 0
(默认情况下)和String[][] array= new String[size][];
创建一个大小为0的数组。
因此,您的数组的大小为0,当您尝试分配像array[i] = prepareArray();
这样的值时,您会遇到异常。