1. 程式人生 > 實用技巧 >關於使用鍵盤錄入Scanner錄入不對應型別的錯誤

關於使用鍵盤錄入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 });

錯誤效果如圖:

修改之後效果圖: