Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Comparing ArrayList item to User Input String

I have seen other threads on this, but I still don't understand the best approach. Issue is as started: One can't compare user input that is a String to an arrayList item (object). My List will be over 40 items.

So when I try to compare classesList.get(0) to the user input mage. It won't work.

List<String> classesList = new ArrayList<String>();
classesList.add("mage");
classesList.add("warrior");
classesList.add("thief"); 

Scanner input = new Scanner(System.in);

String input = input.next();

for (int counter = 0; counter < classesList.size(); counter++) { 
    if (input == classesList.get(counter)) {
        //won't run body since can't compare
    }
}

I found some who converted the arrayList to be a String. But I am unsure how I could then easily search through my list. I'd much rather leave it as a List instead. Is the best method to this approach?

String[] classesArray = classesList.toArray(new String[classesList.size()]);
like image 512
Josh Avatar asked Dec 20 '25 02:12

Josh


1 Answers

I think you have to see if input string exist in the ArrayList, you have to use contains() method.

   if(classesList.contains(input)) {
       //Found in the arraylist.
   }

But with you method, you can't compare strings using == operator. You should use equals() method for comparision

List<String> classesList = new ArrayList<String>();
classesList.add("mage");
classesList.add("warrior");
classesList.add("thief"); 

Scanner input = new Scanner(System.in);

String input = input.next();
boolean isExist = false;
for (String item : classesList) { 
    if (input.equals(classesList.get(counter))) {
        //Your logic if it's there.
         isExist = true;
         break;
   }
}

 if(isExist) {
     //Found in the arraylist.
 }

Also if you want to make this comparision with ingnoring the case, you shoudl consider using equlasIgnoreCase() method instead of equals() method.

like image 137
Vallabh Patade Avatar answered Dec 22 '25 14:12

Vallabh Patade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!