My task is: The program should read items from the user. When all the items from the user have been read, the program prints the information of each item.
For each item, its identifier and name should be read. If the identifier or name is empty, the program stops asking for input, and prints all the item information. Modify the program so that after entering the items, each item is printed at most once. Two items should be considered the same if their identifiers are the same (there can be variation in their names in different countries, for instance).
If the user enters the same item multiple times, the print uses the item that was added first. I have done the code below, but it will still add items with the same identifier.
Why? How can I fix it?
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> itemsName = new ArrayList();
ArrayList<String> itemsIdentifier = new ArrayList();
while(true){
System.out.println("Identifier? (emppty will stop)");
String identifier = scanner.nextLine();
if( identifier.isEmpty()){
break;
}
System.out.println("Name? (emppty will stop");
String name = scanner.nextLine();
if(name.isEmpty()){
break;
}
if(!(itemsIdentifier.contains(identifier))){
itemsIdentifier.add(identifier);
}
if(!(itemsName.contains(name))){
itemsName.add(name);
}
}
System.out.println("==Items==");
int j = 0;
for(String i: itemsIdentifier){
System.out.println(i + ": "+ itemsName.get(j));
j++;
}
}
}
I think the problem with your code is that you are adding name
into itemsName
list even when you are not adding identifier
into itemsIdentifier
list in the following lines
if(!(itemsIdentifier.contains(identifier))){
itemsIdentifier.add(identifier);
}
if(!(itemsName.contains(name))){
itemsName.add(name);
}
Ideally shouldn't you either add both name and identifier or don't add any?
You have a while(true)
loop which will keep going indefinitely, you are breaking the loop only if the user input is empty, but you are not doing anything when the lists already contain an identifier more than once. (You are adding to the list if you have a unique identifier).
EDIT I have other misgivings on the code above (I am assuming that this is an assignment), but since I do not know if you built this on top of what the lecturer gave you, I can only speculate. Some thoughts on the code above:
Record
object.equals
method.Record
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With