如何在Java中打印出数组的偶数索引?
问题描述:
我应该编写一个程序,使用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]);
}
}
}
答
你可以改变你的for循环,摆脱内部IF的...
for(int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
答
就绝对相同的使用Java的东西8 Stream
API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
答
我认为这将是足够
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
答
这是我做的,它的工作原理:还我没有打印出指数[0]因为在技术上它甚至不是这样,为什么我在2开始for循环。你的帖子确实帮了我很多。我也感谢所有花时间发布答案的人。
import java.util.Scanner;
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 = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}
'如果(阵列[数+ 1]%2 == 0)' - >你不希望被检查'index'代替? – JonK
你能更清楚地知道它是如何“不工作”的吗?你有没有尝试过在调试器中寻找问题?显然你正在测试错误的值。 –