英文:
How can I store vector of vectors into a 2d array in java
问题
以下是翻译好的内容:
在 Java 代码片段中:
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); // 这一行会抛出 ArrayStoreException 异常
for (int[] c : ar) {
System.out.println(c);
}
}
}
我想将向量 `vec` 的元素存储在名为 `ar` 的二维数组中。
我需要帮助解决 `ArrayStoreException` 异常,并且想要将 `vec` 的元素存储到 `ar` 中。
请帮忙解决。
英文:
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.
答案1
得分: 0
Vector是1维的。Array也是1维的。Vector.copyInto()方法接受一个i维数组作为参数。
如果你想要将一个Vector的Vectors复制到一个2维Array中,那么你需要通过2个维度来循环进行复制。
所以代码会是这样的:
Object[][] rows = new Object[vec.size()][];
for (int i = 0; i < vec.size(); i++)
{
Vector<Object> vectorRow = ((Vector)vec.get(i));
Object[] arrayRow = new Object[vectorRow.size()];
vectorRow.copyInto(arrayRow);
rows[i] = arrayRow;
}
我需要帮助处理ArrayStoreException异常
那是一个运行时异常。首先,你需要关注正确的算法来复制数据。然后,如果你想捕获异常,你可以在整个算法中添加try/catch块。
英文:
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:
Object[][] rows = new Object[vec.size()][];
for (int i = 0; i < vec.size(); i++)
{
Vector<Object> vectorRow = ((Vector)vec.get(i));
Object[] arrayRow = new Object[vectorRow.size()];
vectorRow.copyInto( arrayRow );
rows[i] = arrayRow;
}
> I need help to deal with ArrayStoreException
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论