-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);
        }
    }
}
4

2 回答 2

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

这应该是outside the loop您填充地图的位置。

于 2012-10-22T15:58:57.717 回答
0

我不知道你到底想做什么,但 FOR 循环真的很少见,你循环遍历所有标记,但总是得到位置 5 和 6,所以那里不需要 for,只得到这两个位置从每个令牌。

        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 可以在地图上找到该键。

于 2012-10-22T16:38:11.723 回答