2014-12-09 40 views
0

我試圖從列出的文件,其中包含一個陳述文字打印一行。但該計劃什麼都不做。有人可以幫助我的代碼?由於程序終止,不打印任何東西

import java.io.File; 
import java.util.ArrayList; 
import java.util.Scanner; 


public class SearchingArrayLists { 
public static void main(String[] args) throws Exception { 

     ArrayList names = new ArrayList(); 
     Scanner scan = new Scanner(new File("random.txt")); 

     while (scan.hasNext()){ 
     names.add(scan.next()); 
     } 

     if (names.contains("legal")){ 
     System.out.println(scan.next()); 
     } 

     scan.close(); 

    } 

} 

UPDATE:

對不起,去除循環。該文件包含隨機文本,其中有「合法」一詞。該文件被掃描儀事先讀取。

+0

爲什麼空的'for'循環? – Maroun 2014-12-09 13:35:24

+0

'random.txt'包含什麼? 並且該文件正在被掃描儀讀取? – 2014-12-09 13:35:42

+2

是否random.txt含有法律也不會有下一個()這裏所說的:'的System.out.println(scan.next());'因爲你已經在整個文件中重複。 – brso05 2014-12-09 13:36:28

回答

1
Scanner scan = new Scanner(new File("random.txt")); 
    String name = "" ; 
    while (scan.hasNextLine()){ 
    name = scan.nextLine(); 
    if (name.contains("legal")){ 
    System.out.println(name); 
    } 
} 




    scan.close(); 

試試上面的代碼,你甚至不需要列表。我沒有編譯它,所以如果有任何語法錯誤,請刪除。

+0

嘿,這工作很好,謝謝,但我希望它,因此它顯示該單詞的行。我應該讓這個更清楚。謝謝 – 2014-12-09 13:57:16

+0

你試過了嗎?它是不是顯示整條線?對不起,我現在沒有jvm和ide現在 – Panther 2014-12-09 13:59:13

+0

是的,我試過它打印這個詞。我想它所以它打印行雖然 – 2014-12-09 14:01:03

2

System.out.println(scan.next());會拋出一個異常,因爲您在使用while (scan.hasNext())循環中的所有輸入之後調用它。

但它甚至有可能不會達到那個異常,如果您names列表中不包含精確匹配字符串「合法」。