hashmap.get()返回错误的值,即使它们在地图中都是正确的 [英] hashmap.get() returning wrong values even though they are all correct in the map
问题描述
目标是采用String []长度36,它将是一个从1x1到6x6的6x6数组,然后打印出在2d数组中找到的单词的坐标.很简单.我已经将每个数组项与相应的坐标一起放置在地图中(作为String值,因为我需要返回String).例如,如果我打印所有值,它们将正确打印11到66,但是如果输入是"NO70JE3A4Z28X1GBQKFYLPDVWCSHUTM65R9I",当我应该获取"1166"时,将得到"1271"作为输出.有任何想法吗?这是我的代码.
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");
推荐答案
这是我使用的代码(几乎完全复制/粘贴了),给出了正确的答案:
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
我相信,正如@alfasin
所暗示的那样,问题在于您正在初始化char数组a
的方式,并且一个寄生虫字符正好出现在字符串的开头
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.
这篇关于hashmap.get()返回错误的值,即使它们在地图中都是正确的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!