I have a problem with matching a string against a string arraylist and开发者_开发百科 getting a single boolean result. Basically, I used a for loop to do the matching and all I get was a series of boolean. But what I want is that when there is one amongst all the boolean, it will return one single value and if it is all , then it will return a single value. The code is as below. Help T.T
import java.util.*;
public class NewClass {
public static void main(String [] args){
ArrayList <String> aList = new ArrayList <String>();
aList.add("I");
aList.add("Love");
aList.add("You");
aList.add("Black");
aList.add("Colored");
aList.add("Ferrari");
boolean match;
for(int i = 0; i < aList.size();i++){
match = aList.get(i).equals("Red");
System.out.print(match);
}
}
}
contains should do the trick
if (aList.contains("Red")) {
//cool
}
You should break out of the loop once you have found a match, and print the result outside the loop, as shown below:
boolean match = false ;
for(int i = 0; i < aList.size();i++){
match = aList.get(i).equals("Red");
if(match){
break;
}
}
System.out.print(match);
Alternatively, a shorter approach is to not use a loop but call the contains
method of the list instead:
boolean match = aList.contains("Red");
System.out.println(match);
精彩评论