线程主java.util.InputMismatchException中的异常

pra*_*rak 1 java

我正在实现一个简单的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));
    }
}
Run Code Online (Sandbox Code Playgroud)

当我从nextInt()获取输入时,Scanner会抛出InputMismatchException异常,但如果我从nextLine()获取输入然后将其解析为int,那么我的代码就会正常运行.请解释一下.

如果我可以将字符串输入解析为任何类型,为什么我应该使用nextInt()或nextDouble().

Era*_*ran 6

sc.nextInt() 不读整行.

假设你输入

John
20
Dan
24
Run Code Online (Sandbox Code Playgroud)

现在让我们看看每个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 
Run Code Online (Sandbox Code Playgroud)

以下小改动将克服该异常:

for(int i=0;i<5;i++)
{
   String name=sc.nextLine();
   int age=sc.nextInt();
   sc.nextLine(); // add this
   map.put(name,age);
}
Run Code Online (Sandbox Code Playgroud)

现在,Scanner将正常运行:

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)
Run Code Online (Sandbox Code Playgroud)