hashmap.get()返回错误的值,即使它们在地图中都是正确的

时间:2014-05-31 00:02:53

标签: java arrays hashmap

目标是获取String []长度36,它将是1x1到6x6的6x6数组,然后打印出2d数组中找到的单词的坐标。很容易。我已经使用相应的坐标将每个数组项放入地图中(作为String值,因为我需要返回一个String)。如果我打印它们正确打印的所有值11到66,但是如果输入是“NO70JE3A4Z28X1GBQKFYLPDVWCSHUTM65R9I”,例如当我得到“1166”时,我得到“1271”作为输出。有任何想法吗?这是我的代码。

     int rcounter = 1;
    int ccounter = 1;
    HashMap<String, String> soup = new HashMap<String, String>();
    for (int i = 0; i < a.length; i++) {
        if (ccounter == 7) {
            ccounter = 1;
            rcounter++;}
        String row = Integer.toString(rcounter);
        String column = Integer.toString(ccounter);
        soup.put(a[i], row + column);
        ccounter++;
        if (i == 36) {
            break; }
            System.out.println(row+column); }


    return soup.get("N") + soup.get("I");

1 个答案:

答案 0 :(得分:1)

这是我使用的代码(几乎完全复制/粘贴),它给出了正确的答案:

public class Testtest {

    public static void main(String[] args) {
        char a[] = "NO70JE3A4Z28X1GBQKFYLPDVWCSHUTM65R9I".toCharArray(); // line added to have array "a"

        int rcounter = 1;
        int ccounter = 1;
        Map<String, String> soup = new HashMap<String, String>();
        for (int i = 0; i < a.length; i++) {
            if (ccounter == 7) {
                ccounter = 1;
                rcounter++;}
            String row = Integer.toString(rcounter);
            String column = Integer.toString(ccounter);

            soup.put(new String(""+a[i]), row + column); // line changed to add a String, not a Char, to HashMap
            ccounter++;
            if (i == 36) {
                break;
            }
            System.out.println(row+column);
        }

        System.out.println("result: " + soup.get("N") + soup.get("I")); // changed to display result, rather than return it
    }
}

使用此代码,几乎没有任何更改,并使用您提供的String,我得到了正确的结果:

result: 1166

我相信,正如@alfasin暗示的那样,问题在于你正在初始化你的char数组a,而且一个寄生虫角色出现在第一个地方,就在字符串的开头。