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