2012-10-22 27 views
-2

我正在嘗試讀取一個csv文件並將其內容存儲在散列映射中,並檢查散列映射中是否存在特定的鍵。如何在散列表中輸入元素並檢查特定鍵的存在?

這裏是我的代碼,請讓我知道我錯了,因爲讀音字螞蟻能夠找出我的錯誤

import java.io.*; 

import java.text.SimpleDateFormat; 

import java.util.*; 

public class PoolCsv { 

    public static void main(String[] args) { 

     try { 

      Calendar currentdate = Calendar.getInstance(); 
      SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); 
      String presdate = dateformat.format(currentdate.getTime()); 
      currentdate.add(Calendar.DAY_OF_YEAR, 4); 
      String futdate = dateformat.format(currentdate.getTime()); 
      System.out.println(presdate); 
      System.out.println(futdate); 
      String poolcsv = "D:\\pool_items.csv"; 
      BufferedReader br = new BufferedReader(new FileReader(poolcsv)); 
      String lines = null; 
      String[] tokens = null; 
      String startdate = null; 
      String enddate = null; 
      HashMap<String, String> hash = new HashMap<String, String>(); 
      while ((lines = br.readLine()) != null) { 
       tokens = lines.split(","); 
       for (int i = 0; i <= tokens.length; i++) { 
        startdate = tokens[5]; 
        enddate = tokens[6]; 
       } 

       hash.put(startdate, enddate); 

       boolean flag = hash.containsKey(presdate); 
       if (flag) { 
        System.out.println("value exists"); 
       } 
      } 

     } catch (IOException io) { 
      System.out.println(io); 
     } 
    } 
} 
+2

像你這樣做:'放''添加元素和'containsKey'來檢查一個鍵是否存在....你在問什麼? – assylias

+0

在if條件下似乎沒有任何工作 – user1690973

回答

2
boolean flag = hash.containsKey(presdate); 
if(flag){ 
    System.out.println("value exists"); 
} 

這應該是outside the loop您在其中填充地圖。

+0

if條件中還沒有執行任何內容 – user1690973

+0

您確定'presdate'在散列映射中嗎?輸入格式可能不同,或者當前日期沒有任何輸入,在這種情況下containsKey()應該返回false。 –

+0

是的,文件 – user1690973

0

我不知道你想要做什麼,但是FOR循環非常罕見,你循環了所有的標記,但是總是獲得位置5和6,所以不需要在那裏,只有從每個令牌獲得這兩個職位。

 while ((lines = br.readLine()) != null) { 
      tokens = lines.split(","); 
      //I dont think you neeed this for. 
      for (int i = 0; i <= tokens.length; i++) { 
       startdate = tokens[5]; 
       enddate = tokens[6]; 
      } 

      hash.put(startdate, enddate); 

      boolean flag = hash.containsKey(presdate); 
      if (flag) { 
       System.out.println("value exists"); 
      } 
     } 

也許你可以有一些信息,如果您打印presdate和STARTDATE,以確保兩個字符串具有相同的格式。 yyyy-MM-dd(注意分隔符)和字符串非常相等,因此ContainsKey可以在地圖上找到該鍵。

相關問題