将第二列和第三列从2d数组检索到数组

时间:2016-02-17 15:38:34

标签: java arrays

我有一个Java代码,它将输出3列双整数,就像这样(1列,2列,3列):

( 0.09,  0.27,  0.01) 
( 0.00, -0.00,  0.26)  
( 0.02, -0.02,  0.24) 
( 0.22, -0.11, -0.03) 

现在,我希望将第二列中的所有值存储到一个数组中,并将第三列中的值存储到另一个数组中。有没有办法可以修改它以便实现这一目标?

这是我的部分代码:

for (int i = 0; i < termVectors.length; ++i) {
    System.out.print("(");
    for (int k = 0; k < 3; ++k) {
    if (k > 0) System.out.print(", ");
    System.out.printf("% 5.2f",termVectors[i][k]);
    }
    System.out.print(")  ");
}

谢谢!

2 个答案:

答案 0 :(得分:1)

请尝试以下代码。

 int[] secondColVal = new int[termVectors.length];
int[] thirdColVal = new int[termVectors.length];

for (int i = 0; i < termVectors.length; ++i) {
    System.out.print("(");
    for (int k = 0; k < 3; ++k) {
    if (k > 0) System.out.print(", ");
    System.out.printf("% 5.2f",termVectors[i][k]);
    if(k==1)
    secondColVal[i] = termVectors[i][k];
    if(k==2)
    thirdColVal[i] = termVectors[i][k];
    }
    System.out.print(")  ");
}

答案 1 :(得分:1)

这应该可以满足你的需要:)

// since you're using the length multiple times, store it in a variable!
int len = termVectors.length;
// declare two arrays to represent your second and third columns
int[] secondColumn = new int[len];
int[] thirdColumn = new int[len];

for (int i=0;i<len;i++)
{
    // populate your arrays
    secondColumn[i] = termVectors[i][1];
    thirdColumn[i] = termVectors[i][2];
}