0

i have tried like this

public Set<String> getEvens() {
    Set<String> evens = new TreeSet<String>();
    for (String a : list) {
        if (a % 2 == 0) {
            int x = Integer.parseInt(a);
            evens.add(x);
        }
    }
}

and this

public Set<String> getEvens() {
    Set<String> evens = new TreeSet<String>();
    for (String a : list) {
        int x = Integer.parseInt(a);
        if (a % 2 == 0) {
            evens.add(a);
        }
    }
}

but neither work and I'm not sure what else to try. I haven't used parseInt in a while and might be doing it wrong also

These are the errors I get:

error: bad operand types for binary operator '%'
error: no suitable method found for add(int)

5 Answers5

3

The second will almost work, it's just your parseInt is not within the for's curly braces, you will also need to use % on x (the int), not a (the String).

public Set<String> getEvens()
{
    Set<String> evens = new TreeSet<String>();
    for (String a : list)
    {
        int x =Integer.parseInt(a);
        if (x % 2==0)
        {
            evens.add(a);
        }
    }
}
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
0

The second one is right, except use x%2 instead of a%2

ia.solano
  • 548
  • 3
  • 10
  • 23
0

Operator % works only on numeric types in Java. Modify your second solution like this:

if (x % 2 == 0) {
    evens.add(a);
}

There is x instead of a in the if-condition.

0
public Set<String> getEvens(List<String> list) {
    Set<String> evens = new TreeSet<String>();
    // modify for(String a:list){
    for (String a : list) {
        int x = Integer.parseInt(a);
        {
            //modify if (a % 2 == 0) {
            if (x % 2 == 0) {
                evens.add(a);
            }
        }
    }
    // modify add this }

}
sunysen
  • 2,265
  • 1
  • 12
  • 13
0

Both examples have a different error, but they are unrelated to parsing int.

Example 1: events.add(x), events takes Strings while x is int.
Example 2. a%2 is wrong, a is String.

Learning how to read stacktraces is fundamental in Java and would easily have helped you here: What is a stack trace, and how can I use it to debug my application errors?

Community
  • 1
  • 1
Homyk
  • 364
  • 2
  • 7