Java如何获取数组的第二个元素

时间:2017-05-04 01:29:51

标签: java arrays

我正在处理一项要求用户输入未定数量的整数的赋值,然后这些数字将用于其他计算。但是,例如,如果我有这6个数字。 1 2 3 4 5 6我想从输入中只提取2 4和6我该怎么做? (注意这只是一个例子,用户可以输入20个不同的数字,或者只有4个)我只想选择每一个元素。要添加更多信息,我需要数组中的第一个数字用于一次计算,然后第二个用于另一个计算,然后是第一个和第二个。基本上我希望能够将每个偶数数组索引号分配给一个整数,并将每个奇数数组索引号分配给另一个整数。像这样:

" if(i%2 == 0){int first = numbers [i]; System.out.println("这是第一个" +第一个)} 否则if(i%2 == 1){int second = numbers [i]; System.out.print("这是第二个。" +秒);}" 但是当我这样做时,它只出现在第一个......

4 个答案:

答案 0 :(得分:0)

  

由于数组索引从// all of the second elements in numbers are collected into partial array int[] partial = new int[numbers.length >> 1]; // the initial value of i=1 means iterate the first second element at first // i+=2 means iterate the next second element in array for(int i=1;i<numbers.length;i+=2){ partial[(i-1)>>1] = numbers[i]; } 开始,你需要收集数组中索引为奇数的所有元素。

{{1}}

答案 1 :(得分:0)

所以只是为了澄清你想要数组的每一次迭代而没有数字的顺序有任何影响?那么数字数组可能是4,2,6,8,在这个例子中返回值应该是2和8?

如果是这种情况,那么您可以将for循环指定为仅每秒迭代读取一次。

要做到这一点,你需要数组的长度。

int arrLength = arr.length;
for (int i = 1; i < arr.length; i = i+2) {
#dosomething
}

答案 2 :(得分:0)

如果您熟悉Java 8流,那么您可以使用IntStream生成索引,然后选出每个奇数:

int[] everySecond = IntStream.range(0, array.length)
    .filter(i -> i % 2 == 1).mapToInt(i -> array[i]).toArray();

答案 3 :(得分:0)

    // This is from user
    int[] userInput = {};

    int[] pickedNumbers = new int[userInput.length/2];
    if(userInput.length > 1)
    {
        for (int i = 1; i < userInput.length; i = i + 2)
        {
            pickedNumbers[i / 2] = userInput[i];
        }
    }
    // pickedNumber is  the array you can use.