Home > database >  Getting the product ID (integer) in Java
Getting the product ID (integer) in Java

Time:06-01

I've come across a problem where the user is supposed to input (by a Scanner) an ID of an object. It should be one of the 4-digited numbers I've put for each product that's on my "ff" list (either 1234 or 5678 or 9012 or 2345 or 7890). And if they enter a number (ID) that is not on the list, it should output a sentence telling the user they made a mistake.

Whatever I input on a console I get "You've made a mistake! There's no product with such ID!" as an output. Even if I input the number that IS on my list.

System.out.println("I'm displaying boots:\n");

List<FemaleFootwear> ff = new ArrayList<FemaleFootwear>();
ff.add(new FemaleFootwear(1234, "Boots 1", 180));
ff.add(new FemaleFootwear(5678, "Boots 2", 190));
ff.add(new FemaleFootwear(9012, "Boots 3", 150));
ff.add(new FemaleFootwear(3456, "Boots 4", 140));
ff.add(new FemaleFootwear(7890, "Boots 5", 220));
System.out.println(ff);

System.out.println("For shopping type 1, for going back to the menu type 2.");
int option = sc.nextInt();

if (option == 1) {
    System.out.println("Please enter the product ID:\n");
    int option2 = sc.nextInt();
    if (option2 == ff.indexOf(0)) {
        while (ff.contains(option2)){
        System.out.println("You've chosen the product "   option2);
        }
        }else {
            System.out.println("You've made a mistake! There's no product with such ID!");

    }
}

So for example, if I would type '1234', which is the product named 'Boots 1', the output should be "You've chosen the product 1234". But if I input a number that doesn't exist on the list (or a letter) it should show this error.

CodePudding user response:

indexOf(Object o) requires that you give an actual Object contained in the list. In order to search for objects in the list (including with .contains()), you need to implement equals and hashcode on your class...

I think you meant ff.get(0), not ff.indexOf(0), and even still, you cannot compare an integer with an object in your list using ==, or .equals(), as that would never match.


Instead, you need to search the list by their IDs, and you don't need a while loop.

System.out.println("Please enter the product ID:\n");
int option2 = sc.nextInt();
Optional<FemaleFootwear> search = ff.stream()
    .filter(footwear -> footwear.getID() == option2)
    .findFirst();
if (search.isPresent()) {
    System.out.println("You've chosen the product "   option2);
} else {
    System.out.println("You've made a mistake! There's no product with such ID!");
}

Keep in mind that "4 digit numbers" that start with any leading zeroes, aren't "4 digit numbers" , so you might not want to use an integer to represent that.

  • Related