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

标签 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));
    }
}

当我从 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/

相关文章:

java - 在 jdk 1.7 上交叉编译 : jdk1. 6

java - 编码/解码 Base64 失败

java - 强制更改 Java 中的库

java - 如何使用 Java 8 运行 Vertx

java - 对于空列表中的每个循环

java - 野蝇 10 号和 jackson 2 号

java - 该列表未传输到数据库中

java - (何时)try-with 是否应该包含 AutoCloseable 构造函数?

java - Context,DataSource 描述了什么?

XSL中的Java调用,参数类型错误