The snippet in the java code is here:
public class MatrixUsingVectors {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
Vector<Vector<Integer> > vec= new Vector<Vector<Integer> >();
for(int i=0;i<3;i++)
{
Vector<Integer> op= new Vector<Integer>(3);
for(int j=0;j<3;j++)
{
op.add(sc.nextInt());
}
vec.add(op);
}
System.out.println(vec);
int [][] ar= new int[vec.size()][3];
vec.copyInto(ar);// this line throws ArrayStoreException
for(int[] c: ar)
{
System.out.println(c);
}
}
}
I want to store the elements of vector vec
in a 2d array named ar
.
I need help to deal with ArrayStoreException
and want to store the elements of vec
into ar
.
Please help.
Vector is 1 dimensional. Array is 1 dimensional. The Vector.copyInto() method takes a i dimensional array as a parameter.
If you want to copy a Vector of Vectors into a 2 Array, then you need to loop through the 2 dimensions to do the copy
So the code would be something like:
That is a run time Exception. First you need to worry about the proper algorithm to copy the data. Then if you want to catch the exception you add a try/catch block to the entire algorithm.