2013-04-16 142 views
0

我目前正在編寫該程序,我需要從文本文件中讀取信息,然後將讀取的信息與用戶輸入進行比較並輸出消息,說明它是否是是否匹配。將用戶輸入字符串與從文本文件中讀取的字符串進行比較

目前有這個。該程序正在讀取指定的數據,但我似乎無法在最後正確比較字符串並打印結果。

代碼低於任何幫助將不勝感激。

import java.util.Scanner;  // Required for the scanner 
import java.io.File;    // Needed for File and IOException 
import java.io.FileNotFoundException; //Required for exception throw 

// add more imports as needed 

/** 
* A starter to the country data problem. 
* 
* @author phi 
* @version starter 
*/ 
public class Capitals 
{ 
    public static void main(String[] args) throws FileNotFoundException // Throws Clause Added 
    { 
     // ask the user for the search string 
     Scanner keyboard = new Scanner(System.in); 
     System.out.print("Please enter part of the country name: "); 
     String searchString = keyboard.next().toLowerCase(); 

     // open the data file 
     File file = new File("CountryData.csv"); 

     // create a scanner from the file 
     Scanner inputFile = new Scanner (file); 

     // set up the scanner to use "," as the delimiter 
     inputFile.useDelimiter("[\\r,]"); 

     // While there is another line to read. 
     while(inputFile.hasNext()) 
     { 
      // read the 3 parts of the line 
      String country = inputFile.next(); //Read country 
      String capital = inputFile.next(); //Read capital 
      String population = inputFile.next(); //Read Population 

      //Check if user input is a match and if true print out info. 
      if(searchString.equals(country)) 
      { 
       System.out.println("Yay!"); 
      } 
      else 
      { 
       System.out.println("Fail!"); 
      } 
     } 

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

回答

0

我猜你的比較由於區分大小寫而失敗。

如果您的字符串比較不是CASE-INSENSITIVE?

0

這裏有幾個可能的問題。首先,您將searchString轉換爲小寫。 CSV中的數據是否也是小寫?如果不是,請嘗試使用equalsIgnoreCase。另外,在我看來,你應該能夠匹配部分國家名稱。在這種情況下,equals(或equalsIgnoreCase)只有在用戶輸入完整的國家名稱時纔有效。如果您只想匹配一部分,請改爲使用contains

1

您應該嘗試從用戶界面(可見窗口)中的textField中讀取輸入,用戶放置國家並通過原始輸入縮短代碼(只有在屏幕上有可視窗口時)

我沒有掃描儀的豐富經驗,因爲他們在使用掃描儀時傾向於使應用程序崩潰。但我對相同的測試代碼並僅包括該文件的掃描儀不崩潰我的應用程序看起來像以下:

Scanner inputFile = new Scanner(new File(file)); 

    inputFile.useDelimiter("[\\r,]"); 
    while (inputFile.hasNext()) { 
     String unknown = inputFile.next(); 
     if (search.equals(unknown)) { 
      System.out.println("Yay!"); 
     } 
    } 

    inputFile.close(); 


我覺得比較字符串中的一個文件,最簡單的方法是添加用戶輸入國家的可見窗口,以及將輸入讀取爲字符串,其中String str = textField.getText();

相關問題