Ran into a little problem and I’m not entirely sure why this code won’t work.
I have a 2d arraylist:
List<List<String>> matrix = new ArrayList<List<String>>();
I have a button that adds an arraylist to the matrix based on user input. But before user input is added, I need the button to search for if that string already exists.
The code I have doesn’t produce any errors, but it doesn’t seam to discriminate between existing and none existing strings except for the very first element. It adds everything the user puts in regardless of it’s existence. Also the code will only function if the matrix array already has some elements in it, if the matrix is empty, the code won’t work at all. What am I doing wrong?
String name = NameTXT.getText();
String amount = CountTXT.getText();
for (int i = 0; i < matrix.size(); i ++){
String search = matrix.get(i).get(0);
if (name.equals(search)){
OutputTXT.setText("Item already exists");
break;
} else {
List<String> col = new ArrayList<String>();
col.add(name);
col.add(amount);
matrix.add(col);
OutputTXT.setText(amount +" "+ name +" added");
break;
}
}
separate searching for item and item insertion:
actually, it would be better to design in abstract way and use the language tools to solve your problem, for example the list would be easier to work if its List of item:
then the list would be:
when you need to search: