My code is almost ready I just can't solve a simple problem. I want to add and identification code and the item attched to it in an ArrayList. Example, parentheses are just to clearify what I want to do, they are not part of code or output:
- 3ZU2SD34: The Elder Scrolls (-! added)
- 9ZU5SD54: Fifa 21 (-! added)
- 3ZU2SD34: The Elder Scrolls (-! not added, ID already on the list)
- 3ZU2SD34: Final Fantasy (-! not added, ID already on the list)
- 4ZU8SD89: NBA 2K22 (-! added)
...and so on.
My code looks like this:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Item> items = new ArrayList<>();
while (true) {
System.out.println("Identifier? (empty will stop)");
String identifier = scanner.nextLine();
if (identifier.isEmpty()) {
break;
}
System.out.println("Name? (empty will stop)");
String name = scanner.nextLine();
if (name.isEmpty()) {
break;
}
/*if (!items.contains(identifier)){ This doesn't work
items.add(new Item(identifier, name));
}*/
if (!items.contains(new Item(identifier,name))) {
items.add(new Item(identifier, name)); //this works fine, but I want to skip even if only the ID is equal
}
}
System.out.println("");
System.out.println("==Items==");
for (Item lines : items) {
System.out.println(lines);
}
}
}
Output:
Identifier? (empty will stop)
1234
Name? (empty will stop)
Test1
Identifier? (empty will stop)
1234
Name? (empty will stop)
Test2
Identifier? (empty will stop)
1234
Name? (empty will stop)
Test1
Identifier? (empty will stop)
5555
Name? (empty will stop)
Test3
Identifier? (empty will stop)
==Items==
1234: Test1
1234: Test2
5555: Test3
My code adds everything execpt identical Items, but I want it to skip same identification too. How can I do it? Probably there is such an easy way, but I can't figure it out.