0
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);
    }
}

Im a little confused on what to do when it tell me to Print the integers at the even indexes of the passed in array.

Steven
  • 3
  • 2
  • Always solve "big" problems by breaking it into smaller ones. First initialize `values` with integers. Then, can you print all of them ? If so post the code of how you do it. – c0der Oct 26 '17 at 04:08

3 Answers3

1

Array indices start at 0, so in this array- int[] nums = {1, 5, 7, 9, -2, 3, 2};, the number 1 is at index 0, 5 is at index 1, 7 is at index 2, and so on. You're asked to print the numbers at the even indices, so - 1, 7, -2, 2.

You access array elements by the array name, and the position, like num[0] gives you 1.

Here's a good starting point to read up more on Arrays.


Looking at your methods, I'm assuming you'll want to use asList() to pass an ArrayList to the printEvenIndex() method. The difference in case of an ArrayList is that you'll be using get(index) method to fetch an element from the arraylist.

Even in that case, you'll need to check that you pass in an even index as the value to .get().

Manish Giri
  • 3,562
  • 8
  • 45
  • 81
0

You can use something like a for loop to iterate through your num[] array starting from 0 and adding 2 to the counter each iteration so it only prints the even indexes.

for (int i = 0; i < nums.length; i+=2)
        {
            System.out.print(nums[i] + " ");
        }

The output of this code would be : 1 7 -2 2

codemonkey
  • 58
  • 1
  • 8
0

I think this is work for you.

public static void printEvenIndex(ArrayList list)
{
    //Print the integers at the even indexes of the passed in array
    System.out.print("Expected Result:\t");

    for(int i=0;i<list.length;i++)
    {
       if((i%2==0)||(i==0)) 
          System.out.print(list[i]+"\t");
    }
}
patjing
  • 21
  • 8