2014-12-09 37 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列表中不包含精确匹配字符串“合法”。