[英]How to fix error: The method put(Integer, Integer) in the type Map<Integer,Integer> is not applicable for the arguments (int, String)
I don't know how to fix this.我不知道如何解决这个问题。 I want to intake a certain number of strings with a hashmap.
我想用 hashmap 接收一定数量的字符串。 I am still a beginner coder and just learned hashmap.
我仍然是初学者,刚刚学习了 hashmap。 PLS help.
请帮忙。
public class Hashmap {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int lines = Scanner.nextInt();
Map<Integer, Integer> hash = new HashMap<Integer, Integer>();
for (int i = 0; i < lines; i++) {
hash.put(i, Scanner.next());
}
}
} }
Scanner.next
returns a String
object. Scanner.next
返回一个String
object。 You cannot put a String
as the value in a map you declared as taking Integer
objects for values.您不能将
String
作为值放入您声明为将Integer
对象作为值的 map 中。 Square peg, round hole.方钉,圆孔。
You have a choice of three ways to fix.您可以选择三种修复方法。
You could change your map declaration to take String
objects as the value.您可以更改您的 map 声明以将
String
对象作为值。 Change this:改变这个:
Map< Integer , Integer > map = new HashMap<>();
… to: … 至:
Map< Integer , String > map = new HashMap<>();
Or, you can collect integers from the Scanner rather than text.或者,您可以从 Scanner 收集整数而不是文本。 Call
Scanner#nextInt
.调用
Scanner#nextInt
。
Or, you can collect text from the scanner, and then transform that text to an integer.或者,您可以从扫描仪收集文本,然后将该文本转换为 integer。 Call
Integer.valueOf
.调用
Integer.valueOf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.