【发布时间】:2018-09-19 02:43:20
【问题描述】:
我正在尝试编写一种方法来搜索特定单词的 ArrayList,然后打印该单词所有出现的位置。
这就是我所拥有的,它可以正常工作,直到我输入要搜索的单词,但它什么也没打印:
import java.util.ArrayList;
import java.util.Scanner;
public class W7E2 {
public static void main(String[]args) {
System.out.println("Please anter words: ");
Scanner sc = new Scanner(System.in);
String []w = sc.nextLine().split(" ");
ArrayList<Words> word = new ArrayList<Words>();
for(int i=0; i<w.length; i++) {
word.add(new Words(w[i]));
}
System.out.println(word);
System.out.println("Please enter the word you want to search: ");
String search = sc.nextLine();
for(Words ws: word) {
if(ws.equals(search)) {
System.out.println(ws.getLocation());
}
}
}
static class Words{
private String wor;
private static int number = -1;
public Words(String wor) {
this.wor = wor;
number++;
}
public int getLocation() {
return number;
}
public String toString() {
return wor;
}
}
}
【问题讨论】: