[英]Hashmap code not passing all the test cases
I was trying to solve a question for Java Hashmaps where we need to search if key is present or not.我试图解决一个关于 Java Hashmaps 的问题,我们需要搜索键是否存在。 If yes, print the String value otherwise print -1.
如果是,则打印字符串值,否则打印 -1。
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Map<Integer,String> hmap=new HashMap<Integer,String>();
Scanner in=new Scanner(System.in);
int length= in.nextInt();
for(int i=0;i<length;i++) {
hmap.put(in.nextInt(),in.nextLine());
}
while(in.hasNext()) {
int number= in.nextInt();
if(hmap.containsKey(number)) {
String value=hmap.get(number);
System.out.println(value);
}
else {
System.out.println(-1);
}
}
in.close();
}
But all test cases are not passing.但是所有的测试用例都没有通过。 Can anyone please help with what is wrong?
任何人都可以帮忙解决什么问题吗?
Scanner has a problem interpreting your input if you use in.nextLine() after in.nextInt().如果在 in.nextInt() 之后使用 in.nextLine(),扫描器在解释您的输入时会出现问题。 It is because the newline (\\n) of your int input (eg 4 ENTER => 4\\n) remains after returning the int via in.nextInt() and is recognized by the in.nextLine().
这是因为您的 int 输入(例如 4 ENTER => 4\\n)的换行符 (\\n) 在通过 in.nextInt() 返回 int 后仍然存在,并且被 in.nextLine() 识别。 As workaround you could use an additional in.nextLine().
作为解决方法,您可以使用额外的 in.nextLine()。
for(int i=0;i<length;i++) {
Integer key =in.nextInt();
in.nextLine();
String line = in.nextLine ();
hmap.put(key,line);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.