public class Exercise2
{
public static void printEvenIndex(ArrayList list)
{
//Print the integers at the even indexes of the passed in array
}
public static void main(String[] args)
{
//instantiate an ArrayList named values nand fill with Integers
//fromt the supplied list
ArrayList<Integer> values = new ArrayList<Integer>();
int[] nums = {1, 5, 7, 9, -2, 3, 2};
System.out.println("Expected Result:\t 1, 7, -2, 2,");
System.out.print("Your Result:\t\t ");
printEvenIndex(values);
}
}
当它告诉我打印传入数组的偶数索引处的整数时,我有点困惑该怎么做。
最佳答案
数组索引从 0 开始,因此在此数组中 - int[] nums = {1, 5, 7, 9, -2, 3, 2};
,数字 1
位于索引 0,5
位于索引 1,7
位于索引 2,依此类推。系统会要求您打印偶数索引处的数字,因此 - 1, 7, -2, 2
。
您可以通过数组名称和位置来访问数组元素,例如 num[0]
为您提供 1。
这是阅读更多有关 Arrays 的良好起点。 .
<小时/>看看你的方法,我假设你会想要 use asList()
将 ArrayList
传递给 printEvenIndex()
方法。 ArrayList
的区别在于您将使用 get(index)
方法从数组列表中获取元素。
即使在这种情况下,您也需要检查是否将偶数索引作为值传递给 .get()
。
关于Java 打印传入数组的偶数索引处的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46945659/