关于使用键盘录入Scanner录入不对应类型的错误

今天发现Scanner键盘录入对象录入不对应的类型的时候下面的Scanner录入会一直使用上一步录入错误时的值,导致程序错误

代码效果如下:

 1     public static void main(String[] args) {
 2         TreeMap<Student, String> treeMap = new TreeMap<>();
 3         ArrayList<Student> list = new ArrayList<>();
 4         ArrayList<String> list1 = new ArrayList<>();
 5         Scanner sc = new Scanner(System.in);
 6         while (list.size() < 3) {
 7             System.out.println("请输入第" + (list.size() + 1) + "个学生的姓名:");
 8             String name = sc.next();
 9             int age = 0;
10             while (true) {
11                 try {
12                     System.out.println("请输入第" + (list.size() + 1) + "个学生的年龄:");
13                     age = sc.nextInt();       //键盘录入出错位置
14                     break;
15                 } catch (Exception e) {
16                     System.out.println("请输入整数!");
17                    // sc = new Scanner(System.in);        需要正确插入改正,帮sc重新开辟空间
18 
19                 }
20             }
21             Student student = new Student(name, age);
22             list.add(student);
23 
24 
25         }
26 
27         while (list1.size() < 3) {
28             System.out.println("请输入第" + (list1.size() + 1) + "个学生的地址:");
29             String dress = sc.next();
30             list1.add(dress);
31 
32 
33         }
34         for (int i = 0; i < 3; i++) {
35             treeMap.put(list.get(i), list1.get(i));
36 
37 
38         }
39         Set<Map.Entry<Student, String>> entries = treeMap.entrySet();
40         entries.stream().filter(s -> s.getKey().getName().startsWith("张")).forEach(s -> {
41             System.out.print("学生信息:");
42             System.out.print(s.getKey());
43             System.out.println(",对应的居住地址是:" + s.getValue());
44 
45 
46         });

 错误效果如图:

 

 

 修改之后效果图:

 

 

posted @ 2020-08-10 19:33  Joker-0927  阅读(215)  评论(0编辑  收藏  举报
// 侧边栏目录