0

In this method I am trying to find a first even integer in an ArrayList (for further use).

However, when I am calling the method I get -1. As much as I know, this means that there is no integer in the list (but there actually are).

Here is the code:

public static int rangeBetweenEvens(ArrayList<Integer> list) {

    int firstEven = 0;

    for (int i = 0; i < list.size(); i++)
    {
         firstEven = list.indexOf((i) % 2 == 0);

    }

    return  firstEven;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Kasparas
  • 89
  • 1
  • 4
  • 9

13 Answers13

6

You are attempting to find the first occurrence of (i) % 2 == 0, however, this isn't doing what you think it is. This expression is evaluated as a boolean expression -- true if i is even and false if it's odd. In the first iteration, i is 0 (even), but true is not found in the list, because integers exist there, so you are returning the result of indexOf -- -1.

Using indexOf is a mistake here, because that searches the list for a specific value. Instead, use get(i) to retrieve the current value, and test it to see if it's even. If it is, return that current index, else keep searching. Return -1 if not found.

rgettman
  • 176,041
  • 30
  • 275
  • 357
3

indexOf returns the index a value was found in, not the value in the index, which you could retrieve with get, or even better, use the enhanced for loop syntax:

public static Integer firstEven(List<Integer> list) {
    for (Integer curr : list) {
         if (curr % 2 == 0) {
             return curr;
         }
    }
    return null;
}

Note, by the way, that Java 8's streaming syntax can help you do this much more elegantly

public static Integer firstEven(List<Integer> list) {
    return list.stream().filter(i -> i % 2 == 0).findFirst().orElse(null);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

You are calculating with the index not with the value. Do it like this:

for (int i = 0; i < list.size(); i++){
    if(list.get(i) %2 == 0){
         return list.get(i);
    }
}
osanger
  • 2,276
  • 3
  • 28
  • 35
1

indexOf(Object o) accepts an element and tries to find it's index in your collection, so you can't get a condition in there as it will search for true|false inside your list which isn't there

You can check and break from the loop when you get the index like :

public static int rangeBetweenEvens(ArrayList<Integer> list) {

        int firstEven = 0;

        for (int i = 0; i < list.size(); i++)
        {
                if(list.get(i) % 2 == 0) {
                        firstEven = list.indexOf(i);
                }

                break;

        }

        return firstEven;
}
Abdelrahman Elkady
  • 2,518
  • 2
  • 21
  • 30
1

The method is written incorrectly. Instead of indexOf you should be using get(i). Ie. the for loop should look like this:

for (int i = 0; i < list.size(); i++)
{
     if(list.get(i) % 2 == 0)
        return i;
}
AnthonyG
  • 11
  • 2
1

You can use the advanced for loop:

for(int i : list){
if(i%2==0)
return i;
}
1

You might find example in this post useful. Based on that, to find the index of the first even number (or return -1 if none found), you do:

    List<Integer> list = Arrays.asList(11, 10, 1, 42, 5, 11, 7);
    int firstEven = IntStream.range(0, list.size())
            .filter(i -> (list.get(i) % 2 == 0))
            .findFirst()
            .orElse(-1);

    System.out.printf("first even at %d", firstEven);
Community
  • 1
  • 1
prook
  • 371
  • 2
  • 13
0

list.indexOf((i) % 2 == 0); condition inside returns Boolean. Most likely that not what you expect.

Your code should be looks like following:

firstEven = -1;
lastEven = 0;
for (int i = 0; i < list.size(); i++) {
    if ( list.get(i) %2 == 0) {
        if (firstEven == -1)  firstEven = list.get(i);
        lastEven = list.get(i);
    }
}
vvg
  • 6,325
  • 19
  • 36
  • Thank you for your answer. However, the problem is that within the same method i will have to find index of the last even number. What suggestions would you have for that? – Kasparas Feb 10 '16 at 17:52
0

Java -8 way of doing it (I say start using Java -8 :P).

List<Integer> l = Arrays.asList(1,3,4,5,2);
Optional<Integer> oi = l.stream().filter(i -> i%2==0).findFirst();
if (oi.isPresent())
System.out.println(oi.get());

Or Like chris says, use :

l.stream().filter(i -> i%2==0).findFirst().ifPresent(System.out::println);
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0
(i) % 2 == 0

This will return either true or false. And there are no true or false as index. Try this:

public static int rangeBetweenEvens(ArrayList<Integer> list) {

        int firstEven = 0;

        for (int i = 0; i < list.size(); i++)
        {
         if (list.get(i) % 2 == 0) {
              firstEven = list.get(i);
              break;
         }

    }

    return  firstEven;
}
Avijeet Ghosh
  • 167
  • 1
  • 8
0

Take a try at this...

for (int i : list)
{
     if(i % 2 == 0)
        return i;
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

You can Use This....

import  java.util.Arrays;
import java.util.Scanner;

public class FirstEvenNumber {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String numbers;
        System.out.println("Enter numbers separated by coma without spaces:");
        numbers = sc.nextLine();
        String[] splited = numbers.split(",");
        sc.close();
        int [] array = Arrays.asList(splited).stream().mapToInt(Integer::parseInt).toArray();
        outerloop:
        for (int num : array){
            if (num%2 == 0){
                System.out.println(num);
                break outerloop;
            }
        }
    }
}
Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Kalle Richter Oct 14 '18 at 08:41
0

with lambda function avoiding the % modulo operator

Function<List<Integer>, Integer> firstEven = ints -> {
  Integer rslt;
  ListIterator<Integer> it = ints.listIterator();
  while( it.hasNext() )
    if( ((rslt = it.next()) & 1) == 0 )
      return( rslt );
  return( null );
};

firstEven.apply( list );

Kaplan
  • 2,572
  • 13
  • 14