0

Hello my goal is to get the user to input some customerID value and some videoID how would I check to make sure the user inputs a correct customerID and videoID in my array I have made for these fields and tell the user they have inputted the wrong ID. This is what i have so far for my code

    public static void HireVideo(){

        System.out.println("Enter Customer ID");
        String customerID = sc.next();
        System.out.println("Enter Video ID");
        String videoID = sc.next();

        HireList.add(new Hire(customerID, videoID));
    }
Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25
user3479903
  • 9
  • 1
  • 3

1 Answers1

1

in an effort to be as close to your code as possible (i.e. what I assume is a static list wrapper class).

public class HireList {
    private static List<Hire> hires = new ArrayList<Hire>();

    public static void add(Hire hire) {
        hires.add(hire);
    }

    public static boolean contains(Hire other) {
        return hires.contains(other);
    }
}

the magic however happens in the Hire class:

public class Hire {
    private String customerId;
    private String videoId;

    public Hire(String customerId, String videoId) {
        this.customerId = customerId;
        this.videoId    = videoId;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 67 * hash + Objects.hashCode(this.customerId);
        hash = 67 * hash + Objects.hashCode(this.videoId);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this.getClass() != obj.getClass()) {
            return false;
        }
        final Hire other = (Hire) obj;
        if (!this.customerId.equals(other.customerId)) {
            return false;
        }
        if (!this.videoId.equals(other.videoId)) {
            return false;
        }
        return true;
    }
}

List<T>.contains(T other) uses the equals method of T, therefore overriding it will allow us to control the behavior of contains.

test:

public static void main(String[] args) {
    HireList.add(new Hire("1", "1"));
    HireList.add(new Hire("2", "2"));

    System.out.println(HireList.contains(new Hire("2", "2"))); //output: true
}

if contains is all you are concerned with though I would suggest using a HashSet as opposed to a ArrayList.

Assaf
  • 1,352
  • 10
  • 19