Edit: added the braces {} and an Eclipse screenshot
I have a problem with a simple assignment to create a class that has an array list to store words from the command-line, with each word appended to the end of the array list, then search the list for a specific word ("the") and prints location of the word's occurences, plus another method to return a new array list with the words at the positions specified by a number.
I wrote the code below. In Eclipse IDE, it doesn't show any errors, but when I tried to run the code by Run Configurations and enter this dummy text: "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.", it doesn't work. I'm not sure why, could you give me advice? Thank you!
import java.util.ArrayList;
import java.util.Scanner;
class Search {
ArrayList<String> list;
public Search(){
list = new ArrayList<String>();
}
public void read(){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
list.add(scanner.next());
}
scanner.close();
}
public void find(String word){
for(int i = 0; i < list.size(); i++) {
if(list.get(i).equalsIgnoreCase(word)) {
System.out.println(i);
}
}
}
public ArrayList<String> subsequence(int[] positions){
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i < positions.length; i++) {
if(positions[i] >= 0 && positions[i] < list.size()) {
result.add(list.get(positions[i]));
}
}
return result;
}
// Testing method within class again
public static void main(String[] args){
Search search = new Search();
search.read();
search.find("the");
for(String s : search.subsequence(new int[]{0, 3, 4}))
System.out.println(s);
}
}
args
in themain
method. Instead you try to read it from standard input. tl;dr:search.list.addAll(Arrays.asList(args));
instead ofsearch.read();
– Johannes Kuhn