I have a file that dumps every line into a position in an ArrayList and I want the user to be able to sort the list to only having lines that have a certain number of words. I can't figure out how to make it print the remaining list (of correct numbered entries).
It starts by finding the first word in the list then it iterates through the CharSequence and checks if the character is equal to a space, ' ' If it is, then it increments nWords by 1 and if nWords is not equal to userInput(the number the user inputs to sort the list by number of words), it should remove that item from the list.
ArrayList<CharSequence> str = new ArrayList();
str.add("Hello");
str.add("Hi there");
str.add("toad");
str.add("i see you");
System.out.println("How many words?");
Scanner scan = new Scanner(System.in);
int userInput = scan.nextInt();
for (int loopNumber = 0; loopNumber < str.size(); ) {
int nWords = 1;
for (int i = 0; i < str.get(loopNumber).length(); i++) {
if ( str.get(loopNumber).charAt(i) == ' ') {
nWords++;
if (nWords != userInput) {
str.remove(loopNumber);
}
}
}
loopNumber++;
}
Try something like this ..... (the compare method might not be the most efficient one!)