Question

I was implementing the method filter that returns a sublist of all the strings in list whose length are larger than 3. I called the filter() in the main function after I added three sample data - Hello Sam Washington. The output should be Hel Sam Was. Suggestions?

import java.util.ArrayList;

public class practice {
    private ArrayList<String> list = new ArrayList<String>();

    public ArrayList<String> filter() {
        for(int i=0; i<list.size(); i++) {
            if(list.get(i).length() > 3)
                list.set(i, list.get(i).substring(0, 3));
        }
        return list;
    }

    public static void main(String[] args) {
        ArrayList<String> list1 = new ArrayList<String>();

        list1.add("Hello");
        list1.add("Sam");
        list1.add("Washington");

        filter();

        for(int i=0; i<list1.size(); i++)
            System.out.println(list1.get(i));
    }
}
Était-ce utile?

La solution 2

You are not instantiating the class Practice. You should do that and fill its list list and then call filter. I am just pasting the main method for you here.

Practice practice = new Practice();
practice.list.add("Hello");
practice.list.add("Sam");
practice.list.add("Washington");

practice.filter();

for(int i=0; i<practice.list.size(); i++)
    System.out.println(practice.list.get(i));

Autres conseils

You're returning list from filter without using the returned value, or actually passing in list1. You can either add the items to list instead, or redo your method like so:

public ArrayList<String> filter(ArrayList<String> toFilter) {
    for(int i=0; i<toFilter.size(); i++) {
        if(toFilter.get(i).length() > 3)
            toFilter.set(i, toFilter.get(i).substring(0, 3));
    }
    return toFilter;
}

and then change the line filter(); to list1 = filter();, so you capture the result of the filtering.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top