gpt4 book ai didi

java - 将数组项放入带有 2 个字符串的 hashmap 中

转载 作者:行者123 更新时间:2023-12-01 16:49:28 25 4
gpt4 key购买 nike

比如说,我有一个与此类似的数组,

{"A", "1", "B", "2", "C", "3"}

我想将它像对一样放入HashMap,我尝试了几种方法,但似乎都不起作用。我创建了一个方法 isDigit() 来检查一个项目是否是数字,

private static boolean isDigit(String str){
try {
Integer.parseInt(str);
}
catch (NumberFormatException nfe){
return false;
}
return true;
}

然后我尝试分成 2 个数组,数字和字母。

for (int i = 0; i <= parts.length; i++) {
if (isDigit(parts[i])) {
numbers[i] = parts[i];
} else {
abcs[i] = parts[i];
}
}

最后,

for (int i = 0; i < numbers.length ; i++) {
map.put(abcs[i], numbers[i]);
}

我打印它们,

for (String each: map.keySet()) {
System.out.println(each + ":" + map.get(each));
}

打印类似的内容,

1
A : null
2
B : null

它应该打印的是,

A : 1
B : 2
C : 3

最佳答案

为什么不通过在 2 秒内递增循环计数器来成对地迭代部分:

for (int i = 0; i < parts.length -1; i += 2) {
map.put(parts[i], parts[i + 1]);
}

关于java - 将数组项放入带有 2 个字符串的 hashmap 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43430514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com