STLCards77
STLCards77

Reputation: 121

hashmap.get() returning wrong values even though they are all correct in the map

Goal is to take in a String[] length 36 and it will be a 6x6 array from 1x1 to 6x6 then print out the coordinates of a word found in the 2d array. Easy enough. I have placed each array item into the map with the corresponding coordinates (as a String value because I need to return a String). If I print all the values they print correctly 11 through 66, but if the input is "NO70JE3A4Z28X1GBQKFYLPDVWCSHUTM65R9I" for example I get "1271" as an output when I should be getting "1166". Any ideas? Here's my code.

     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");

Upvotes: 0

Views: 1412

Answers (1)

AntonH
AntonH

Reputation: 6437

Here is the code I used (almost exactly copy/pasted) which gives a correct answer:

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
    }
}

With this code, with almost no changes, and using the String you provided, I get a correct result:

result: 1166

I believe, as hinted by @alfasin, that the problem is in the way you're initialising your char array a, and that one parasite character is appearing at the first place, right at the beginning of the string.

Upvotes: 1

Related Questions