iT邦幫忙

0

Scanner 輸入導致HashMap 出現 null?

用 Scanner 輸入 ,用規則表示去拆,再放進 Map 裡,但出現 null ?

    Scanner sc = new Scanner(System.in);
    Map<String, String> map = new HashMap<String, String>();
    int n = sc.nextInt();// input <n> Weighted edges 
    while(n >= 0){
        String s = sc.nextLine();
        Matcher edges = Pattern.compile("\\w\\s\\w\\s").matcher(s);
        Matcher weighted = Pattern.compile("\\d+").matcher(s);
        String ed = null;
        String weight = null;
        while(edges.find())
            // System.out.println(edges.group());
            ed = edges.group();
        while(weighted.find())
            // System.out.println(weighted.group());
            weight = weighted.group();
        map.put(ed, weight);
        n--;
    }
    System.out.println(map);
    
    /*output
    4
    a b 1
    c d 3
    a d 2
    b c 2
    {null=null, a b =1, c d =3, b c =2, a d =2
    */
    
        
chichi iT邦新手 3 級 ‧ 2017-08-21 16:17:17 檢舉
我已經解決了
cfox iT邦新手 3 級 ‧ 2017-08-23 09:30:46 檢舉
可以分享一下,說不定以後其他人也有同樣問題。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答