2016-02-28 48 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(); 
} 
相關問題