【发布时间】:2016-11-07 13:56:07
【问题描述】:
我有一个 ArrayList,我在其中搜索所需的元素,然后将所需的部分添加到另一个 ArrayList。问题是,如果我想继续搜索单词,而不仅仅是一个单词,我不知道如何通过循环继续搜索元素。使用迭代器,我将无法搜索到我需要的东西。
public static ArrayList<String> FindWord(){
ArrayList<String> rewrite=new ArrayList<>();//
ArrayList<String> word=Reading();// rewrites the data from one string to other
String userinput=Chat();
for(String elmt:word){
if (elmt.contains(userinput) && elmt.contains("=")) {
String[] parts=elmt.split("\\=");
rewrite.add(parts[1]);
// here I must do something like word.next
}
}
System.out.println(rewrite);
return rewrite; // RETURNS THE SYNONIM OF THE WORD
}
所以,如果我输入“hello”,它会找到我的单词“greeting”,这是我的文本文件中的同义词。如果我输入“awesome”,它会找到“thanks”这个词,但是如果我同时输入它们,它会输入一个空数组,就像没有找到“greeting, Thanks”一样
更新: Reading() 返回:
public static ArrayList<String> Reading() {
Scanner inputreader = null;
try {
inputreader = new Scanner(new FileInputStream("D:\\sinonims.txt"));
}catch (FileNotFoundException e1) { // OPENS FILE WITH SINONIMS
e1.printStackTrace();
System.out.println("File not found");
System.exit(0);
}
ArrayList<String> Sins=new ArrayList();
while(inputreader.hasNextLine()){
String l=inputreader.nextLine();
Sins.add(l); // REWRITES DATA FROM FILE TO ARRATLIST
}
inputreader.close();
System.out.print(Sins);
return Sins;
}
public static String Chat(){
System.out.println("Let's start talking.");
Scanner in=new Scanner(System.in);
String line=in.nextLine();
return line;
}
【问题讨论】:
-
请显示
Reading()返回的内容以及您希望rewrite包含的内容 -
with your statements //在这里我必须做类似word.next的事情,你不要#t next to do next,因为for循环遍历了word中的所有元素
-
您能否提供更多关于您正在阅读的数据以及 Chat() 和 Reading() 返回的数据的详细信息。
-
@cricket_007 完成
-
每次调用
FindWord()方法只接受一个用户输入,而不是多个输入。这就是你想问的吗?因为for(String elmt:word)已经在遍历所有元素。打印出来,你会看到的
标签: java arrays arraylist foreach