Guo Xiuhao
Guo Xiuhao

Reputation: 25

Arraylist matching and returning one single boolean result

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);
        }
        }
    }

Upvotes: 0

Views: 5728

Answers (2)

dogbane
dogbane

Reputation: 274758

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);

Upvotes: 1

fluminis
fluminis

Reputation: 4079

contains should do the trick

    if (aList.contains("Red")) {
        //cool
    }

Upvotes: 4

Related Questions