我正在实现一个简单的 HashMap 程序,它存储人员的姓名和年龄。 这是我的代码:
import java.util.*;
class StoreName {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
String name = sc.nextLine();
int age = sc.nextInt();
map.put(name, age);
}
for (String key : map.keySet())
System.out.println(key + "=" + map.get(key));
}
}
当我从 nextInt() 获取输入时,扫描器抛出 InputMismatchException
异常
但是,如果我从 nextLine() 获取输入,然后将其解析为 int,那么我的代码将正常运行。请解释一下。
如果我可以将字符串输入解析为任何类型,为什么还要使用 nextInt() 或 nextDouble()。
最佳答案
sc.nextInt()
没有读取整行。
假设你输入
John
20
Dan
24
现在让我们看看每个 Scanner 调用将返回什么:
String name=sc.nextLine(); // "John"
int age=sc.nextInt(); // 20
String name=sc.nextLine(); // "" (the end of the second line)
int age=sc.nextInt(); // "Dan" - oops, this is not a number - InputMismatchException
以下小改动将克服该异常:
for(int i=0;i<5;i++)
{
String name=sc.nextLine();
int age=sc.nextInt();
sc.nextLine(); // add this
map.put(name,age);
}
现在,扫描仪将正常运行:
String name=sc.nextLine(); // "John"
int age=sc.nextInt(); // 20
sc.nextLine(); // "" (the end of the second line)
String name=sc.nextLine(); // "Dan"
int age=sc.nextInt(); // 24
sc.nextLine(); // "" (the end of the fourth line)
关于java - 线程主 java.util.InputMismatchException 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31098548/