0

I have been looking for hours, all over the internet and SO, but cannot find anything that I understand! ( Very new at Java )

Upon compiling, it cannot find symbol of the contain method. Here is the code:

public class LotteryTicket {
  private String nameOfBuyer;
  private int[] numberList;

  private boolean search(int val) {
    if (val >= 1 && val <= 50) {
      if (numberList.contains(val)) {
        return true;
      } else {
        return false;
      }
    }
  }

I am very new at learning, and I do not know why this is happening.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Nicole I.
  • 87
  • 1
  • 3
  • 10

2 Answers2

1

int[] is a primitive array and does not have a method .contains(). If you used List<Integer> instead, that would give you a .contains() method to call.

Also, your search method must return a value even when val < 1 or val > 50.

If you need numberList to be an int[], you could try this:

private boolean search(int val) {
    if (numberList != null && val >= 1 && val <= 50) {
        for(int number : numberList) {
            if (number == val) {
                return true;
            }
        }
    }
    return false;
}

Or, you could do this:

private boolean search(int val) {
    if (numberList != null && val >= 1 && val <= 50) {
        return Arrays.asList(numberList).contains(val);
    }
    return false;
}
Jason
  • 11,744
  • 3
  • 42
  • 46
0

The List interface defines the method contains. Think of an interface as a contract that classes can "sign" (in Java this is done with the keyword implements) which says that the class must have certain things in its implementation. A very common implementation of the List interface is ArrayList, but Lists do not work very well with the primitive int type, so what you want to do is make an ArrayList of Integers.

The simplest way to make an ArrayList of Integers is to make an array of Integers first (I know, Java has a lot of weird steps required to get things working).

In addition, you want to make sure that boolean methods always return a boolean value or you will get a compiler error.

Here's a working example:

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class LotteryTicket {
    private String nameOfBuyer;
    private List<Integer> numberList;

    private boolean search(int val) {
        return (val >= 1 && val <=50) && numberList.contains(val);
    }

    public static void main(String[] args) {
        LotteryTicket lt = new LotteryTicket();
        Integer[] numberList = new Integer[] {2, 3, 4, 5, 42, 6};
        lt.numberList = new ArrayList<Integer>(Arrays.asList(numberList));
        System.out.println(lt.search(42)); // prints "true\n"
        System.out.println(lt.search(25)); // prints "false\n"
    }
}
Shashank
  • 13,713
  • 5
  • 37
  • 63