我应该编写一个程序,使用for循环打印出我的数组的偶数索引。例如,如果我创建了一个包含10个数字的数组,它将具有0-9的索引,因此在这种情况下,我会打印索引2,4,6和8中的数字。这是我迄今为止所写的,但它不起作用。请注意,我不打印出数组的偶数。我想要的只是偶数索引。如何在Java中打印出数组的偶数索引?
例子我输入下面的数组: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]);
}
}
}
'如果(阵列[数+ 1]%2 == 0)' - >你不希望被检查'index'代替? – JonK
你能更清楚地知道它是如何“不工作”的吗?你有没有尝试过在调试器中寻找问题?显然你正在测试错误的值。 –