2012-08-08 109 views
0

我已經寫出了以下代碼,我的目標是在提示符處輸入一個字符串,並返回包含此字符串的列表中的任何單詞。我想我只是缺少一些小東西,當我運行程序時,它會打印整個單詞列表。任何幫助,將不勝感激。使用indexOf來搜索包含某些字母的字符串

package assignment1; 

import java.net.*; 
import java.util.ArrayList; 
import java.util.List; 
import java.io.*; 

public class URLReader { 
static List<String> words = new ArrayList<String>(); 

public static void main(String[] args) throws Exception { 
    System.out.println("Please Input A String"); 
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    String letters = br.readLine(); 
    URL oracle = new URL("http://dl.dropbox.com/u/18678304/2011/BSc2/words.txt"); 
    BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream())); 
    String inputLine; 

    while ((inputLine = in.readLine()) != null) 
     words.add(inputLine); 
     in.close(); 

for(int i = 0; i<words.size(); i++) 
{ 
    if(words.get(i).indexOf(letters) >= 0); 
     System.out.println(words.get(i)); 
} 

} 
} 
+1

我瘦k您需要編輯此代碼。你的if語句後面有一個分號,可以儘早終止。 – BlackVegetable 2012-08-08 15:48:02

回答

2

你在你的if語句的結束有;

if(words.get(i).indexOf(letters) >= 0); 
    System.out.println(words.get(i)); 

它應該是:

if(words.get(i).indexOf(letters) >= 0) 
    System.out.println(words.get(i)); 
+0

傻了,非常感謝。 – 2012-08-08 15:53:51

+1

@TimmjyMorrissey你應該在這裏真的使用'String.contains'。 – oldrinb 2012-08-08 15:54:28

2

括號{}不需要一個聲明,但它的安全始終使用:

if(words.get(i).indexOf(letters) >= 0){ 
System.out.println(words.get(i)); 
} 
+1

是的,但是如果他總是在代碼中使用大括號,應該避免這個問題。 – 2012-08-08 16:06:59