我正在将数据从jtable发送到数据库并且它工作正常,但我不知道为什么它会引发一个错误,即Array Index Out Of Bounds 1> = 1 或阵列索引超出界限1> = 1
这是我的代码
public void save()
{
try
{
String Date[] =new String[10];
String Bill_No[] =new String[10];
String M_Id[] =new String[10];
String C_Name[] =new String[10]; // C_Name is array and index 10 means no. of row
String Item_No[]=new String[10];
String Product[]=new String[10];
String Price[] =new String[10];
String Quantity[] =new String[10];
String Amount[] =new String[10];
String Points[] = new String[10];
for(int i=0; i<12; i++) //loop from 0 row to 10
{
Date[i]=jTable1.getValueAt(i,0).toString(); // it get value from 0 row and 0 column
Bill_No[i] =jTable1.getValueAt(i,1).toString();
M_Id[i] =jTable1.getValueAt(i, 2).toString();
C_Name[i]=jTable1.getValueAt(i,3).toString(); // it get value from 0 row and 1 column
Item_No[i] =jTable1.getValueAt(i,4).toString();
Product[i]=jTable1.getValueAt(i,5).toString();
Price[i]=jTable1.getValueAt(i,6).toString();
Quantity[i]=jTable1.getValueAt(i,7).toString();
Amount[i]=jTable1.getValueAt(i,8).toString();
Points[i]=jTable1.getValueAt(i,9).toString();
//similarly for more column
try
{
s=conn.createStatement();
int row=s.executeUpdate( "insert into E_Costumes values('"+Date[i]+"','"+Bill_No[i]+"','"+M_Id[i]+"','"+C_Name[i]+"','"+Item_No[i]+"','"+Product[i]+"','"+Price[i]+"','"+Quantity[i]+"','"+Amount[i]+"','"+Points[i]+"')");
if(row>0)
{
JOptionPane.showMessageDialog(this, "ITEM ADDED SUCCESSFULLY.");
quantity_sub();
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this, ex);
}
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this, ex);
}
}
答案 0 :(得分:3)
for(int i=0; i<12; i++)//0,1,2,3,4,5,6,7,8,9,10,11
| |
^^^^^^^^^^^
But for index 10 and 11 your arrays don't have element
because all arrays will have elements from 0....to...9
如果所有数组的长度都相同,则应将长度声明为常量,
private static final int COMMON_ARRAY_LENGHT = 10;
并在每个数组初始化和循环中使用它,
String Date[] =new String[COMMON_ARRAY_LENGHT];
//..And so on
同时你的循环将是,
for(int i=0; i < COMMON_ARRAY_LENGHT; i++)
答案 1 :(得分:0)
您提供的数组大小为String C_Name [] = new String [10];其中只能添加0到9。 当您尝试在数组中添加超出索引的元素时。
或for(int i = 0; i&lt; 10; i ++) 会解决你的问题 请查看更新的答案