2016-02-28 51 views
1

我目前正在大学入门Java课程中,并且遇到了一些麻烦。上个学期,我们开始使用Python,并且我对它非常了解,并且我会说我现在在编写Python方面非常精通;但Java是另一回事。事情很不一样。无论如何,下面是我当前的任务:我需要编写一个类来搜索文本文档(作为参数传递)以查找用户输入的名称,并输出名称是否在列表中。文本文档的第一行是列表中的名称数量。 的文本文档:从用户输入中搜索文本文件中的名称列表

14 
Christian 
Vincent 
Joseph 
Usman 
Andrew 
James 
Ali 
Narain 
Chengjun 
Marvin 
Frank 
Jason 
Reza 
David 

而且我的代码:

import java.util.*; 
import java.io.*; 

public class DbLookup{ 

    public static void main(String[]args) throws IOException{ 
     File inputDataFile = new File(args[0]); 
     Scanner stdin = new Scanner(System.in); 
     Scanner inFile = new Scanner(inputDataFile); 
     int length = inFile.nextInt(); 
     String names[] = new String[length]; 

     for(int i=0;i<length;i++){ 
      names[i] = inFile.nextLine(); 
     } 
     System.out.println("Please enter a name that you would like to search for: "); 
     while(stdin.hasNext()){ 
      System.out.println("Please enter a name that you would like to search for: "); 
      String input = stdin.next(); 
      for(int i = 0;i<length;i++){ 
       if(input.equalsIgnoreCase(names[i])){ 
        System.out.println("We found "+names[i]+" in our database!"); 
        break; 
       }else{ 
        continue; 
       } 
      } 
     } 
    } 
} 

我只是没有得到我预期的输出,我想不通为什么。

+0

另外一个侧面说明;分配的要求是使用Scanner类;我知道像BufferedReader这样的东西会更有效率,我只需要遵循这个任务。 –

回答

1

试试这个 因为他们有多余的空格

if(input.trim().equalsIgnoreCase(names[i].trim())) 

我遇到你的榜样它运行使用trim()后完美,你已经错过了trim()

+0

这工作!非常感谢。我不敢相信这很简单。 –

0

创建一个单独的scanner类逐行阅读。您也可以使用BufferedReader

final Scanner scanner = new Scanner(file); 
while (scanner.hasNextLine()) { 
    final String str= scanner.nextLine(); 
    if(str.contains(name)) { 
     // Found the input word 
     System.out.println("I found " +name+ " in file " +file.getName()); 
     break; 
    } 
} 
0

你应该trim()自己的价值观如果您使用Java 8:

String[] names; 
try (Stream<String> stream = Files.lines(Paths.get(fileName))) { 
    names = stream.skip(1).toArray(size -> new String[size]); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
相关问题