java - 如何在 Java 中打印出数组的偶数索引?

标签 java arrays

我应该编写一个程序,使用 for 循环打印出数组的偶数索引。例如,如果我创建一个包含 10 个数字的数组,它将具有 0-9 的索引,因此在这种情况下,我将打印出索引 2、4、6 和 8 处的数字。这是我到目前为止所写的,但它不起作用。请注意,我并不是要打印出数组的偶数。我只想要偶数索引。

示例我输入以下数组:3,7,5,5,5,7,7,9,9,3

程序输出:

5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)

我的代码:

public class Arrayevenindex 
{
    public static void main(String[] args)
    {
        int number; // variable that will represent how many elements the user wants the array to have

        Scanner key = new Scanner(System.in);

        System.out.println(" How many elements would you like your array to have");
        number = key.nextInt();
        int [] array = new int [number];

        // let the user enter the values of the array.  
        for (int index = 0; index < number; index ++) 
        {
            System.out.print(" Value" + (index+1) + " :");
            array[index] = key.nextInt();
        }
        // Print out the even indexes 
        System.out.println("/nI am now going to print out the even indexes");
        for (int index = 0; index < array.length; index ++) 
        {
            if (array[number+1]%2==0)
                System.out.print(array[number]);
        }
    }
}

最佳答案

你可以只改变你的 for 循环并摆脱内部 IF...

for( int index = 0; index < array.length; index += 2) {
    System.out.println(array[index]);
}

关于java - 如何在 Java 中打印出数组的偶数索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40915324/

相关文章:

JavaFX:如何获得更多 "dummy/empty Rows"

java - 用java读取声卡的音频输出

java - Broadleaf Commerce 中的特定客户优惠

c - 打印数组列表大小崩溃

java - 为什么我的 Java/Libgdx 9 秒倒计时器不工作?

java - Hive JDBC 连接问题

javascript - 通过其中一个键将对象数组转换为单个对象

javascript - 如何在javascript中通过索引集交换对象值

java - 尝试在 T 数组中使用二分搜索方法递归查找数字时出现 StackOverflowError

python - 使用 numba 中的数组索引数组 (njit) : variable-dimension ndarrays