2017-07-06 43 views
0

我有一個字符串集(字符串1,字符串2,字符串3,字符串4),我想在一個文本文件(input.txt)使用java編碼,我搜索已嘗試使用下面的命令,但它不工作,請幫助。需要Java代碼導入文本文件比較一組字符串

package string; 
import java.io.File; //Required for input file 
import java.io.FileNotFoundException; //Required for exceptioenter code heren throw 
import java.util.Scanner; //required for scanner 

public class strng { 

public static void main(String[] args) throws FileNotFoundException // throws clause added 
{ 

//ask the the for the string to be searched 
    Scanner keyboard = new Scanner(System.in); 
    System.out.print("Please enter part of the string: "); 
    String searchString = keyboard.next().toLowerCase(); 

// open the data file 
    File file = new File("APPD_01_15_16_01.txt"); 
// create a scanner from the file 
    Scanner inputFile = new Scanner (file); 



    // While there is another line to read. 
    while(inputFile.hasNext()) 
    { 
     // read the lines 
     //Read string 

     //Check if user input is a match and if true print out info. 

     if(searchString.contains("samplemachine") 
     { 
      System.out.println("Yup!"); 
     } 
     else 
     { 
      System.out.println("Fail!"); 
     } 
    } 

    // be polite and close the file 
    inputFile.close(); 

} 

} 
+0

從inputFile中讀取字符串的位置在哪裏? – suguspnk

+0

您的示例代碼有點令人困惑,因爲您似乎將用戶鍵盤輸入與搜索「samplemachine」的字符串進行比較,而不是來自文件的輸入。 – munyul

+0

我試圖從用戶輸入搜索,但我的要求是從字符串集 –

回答

-1

根據你的代碼,你沒有閱讀你的inputFile的內容。您應該在循環內逐行讀取inputFile的內容。閱讀完該行後,您現在可以檢查該行是否包含您要查找的內容。

// While there is another line to read. 
while(inputFile.hasNextLine()) 
{ 
    // read the next line from the input file 
    String line = inputFile.nextLine(); 

    //Check if user input is a match and if true print out info. 
    if(line.contains(searchString) 
    { 
     System.out.println(line); 
    } 
} 
0

你的代碼是不是做你說的話你想做的事情。如果你的要求是從字符串集合中搜索,那你爲什麼要比較從用戶那裏得到的輸入?

0

據我所知,這將做你正在尋找的東西。

public static void main(String[] args) throws IOException //Alternatively, you should probably handle this. 
{ 
    //I don't know what your source is for the search strings, 
    //but this will simulate them. 
    String[] toSearch = {"Strings", "to", "search", "for."}; 
    //Simplest way to read a file when no editing is needed. 
    for (String line : Files.readAllLines(FileSystems.getDefault().getPath("input.txt"))) 
    { 
     for (String str : toSearch) 
     { 
      //Simplest way to check if one String contains another. 
      if (line.contains(str)) 
      { 
       System.out.println("Yup!"); 
       //Now that we know the file contains a String, no need to continue. 
       return; 
      } 
     } 
    } 
    //If it even gets to this point, it got through the file with no match. 
    System.out.println("Fail!"); 
} 

一些其他的答案中提到了類似的方法,但是我覺得我的是在覆蓋整個問題,而不是它的特定部分更加完善。