for循环中nextLine()被跳过

for循环中nextLine()被跳过
代码
private static Scanner sc = new Scanner(System.in);

public static void main(String[] args) {
    whiteMouseSortLogic();
}

private static void whiteMouseSortLogic() {
    System.out.println("请输入小白鼠只数:");
    int x = sc.nextInt();
    
    Map<Integer, String> weightHatMap = Maps.newHashMap();
    for (int i = 0; i < x; i++) {
        System.out.println("请输入第" + (i + 1) + "只小白鼠体重和它帽子颜色,用空格隔开:");
        String[] info = sc.nextLine().split("\\s");
        weightHatMap.put(Integer.valueOf(info[0]), info[1]);
    }

    weightHatMap = SortUtils.sortMapByIntKey(weightHatMap);
    weightHatMap.forEach((key, value) -> System.out.println(value));
}

工具SortUtils:

/**
 * 使用Map按key进行排序
 */
public static Map<Integer, String> sortMapByIntKey(Map<Integer, String> map) {
    if (MapUtils.isEmpty(map)) {
        // 这样调用方法的地方就不用担心空指针了
        return Maps.newHashMap();
    }
    Map<Integer, String> sortMap = new TreeMap<>(new MapKeyComparator1());
    sortMap.putAll(map);
    return sortMap;
}

private static class MapKeyComparator1 implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
    }
}

结果
在这里插入图片描述
运行后发现nextLine()被直接跳过,空输入被split之后,info数组值为空,所以Integer.valueOf()方法报NumberFormatException

解决
分析:
nextInt()方法在我们点击Enter键后执行,nextLine()方法也在我们点击Enter键后执行,那么nextInt()方法是只读取了数字,没有读取\n,这个遗留下来的\n被后面的nextLine()读取到了所以才出现这个方法被跳过的假象。
解决方法
在nextInt()方法后用一个nextLine()来读取掉遗留下来的\n
修改后的代码
private static Scanner sc = new Scanner(System.in);

public static void main(String[] args) {
    whiteMouseSortLogic();
}

private static void whiteMouseSortLogic() {
    System.out.println("请输入小白鼠只数:");
    int x = sc.nextInt();
    sc.nextLine();

    Map<Integer, String> weightHatMap = Maps.newHashMap();
    for (int i = 0; i < x; i++) {
        System.out.println("请输入第" + (i + 1) + "只小白鼠体重和它帽子颜色,用空格隔开:");
        String[] info = sc.nextLine().split("\\s");
        weightHatMap.put(Integer.valueOf(info[0]), info[1]);
    }

    weightHatMap = SortUtils.sortMapByIntKey(weightHatMap);
    weightHatMap.forEach((key, value) -> System.out.println(value));
}
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值