我应该编写一个程序,使用 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/