亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

遍歷哈希圖時數組索引越界異常

遍歷哈希圖時數組索引越界異常

Cats萌萌 2021-08-25 17:28:41
我正在嘗試編寫一個 java 程序來找出字符串中出現兩次的單詞數,但出現異常:數組索引越界輸入:2 10 恨愛和平愛和平恨愛和平愛和平8 Tom Jerry Thomas Tom Jerry Courage Tom Courage輸出:1 2完整的代碼是:class GFG {    public static void main (String[] args) {        Scanner sc = new Scanner(System.in);        int t = sc.nextInt();        while(t>0){            int n = sc.nextInt();            int count = 0;            String str = sc.next();            String strArray[] = str.split(" ");            HashMap <String,Integer> wordCount = new HashMap<String,Integer>();            for(int i=0;i<n;i++){                if(wordCount.containsKey(strArray[i])){                    wordCount.put(strArray[i],wordCount.get(strArray[i])+1));                }                else{                     wordCount.put(strArray[i],1);                }            }            for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {                if(entry.getValue()==2)                    count++;            }            System.out.println(count);            t--;        }    }}
查看完整描述

2 回答

?
夢里花落0921

TA貢獻1772條經驗 獲得超6個贊

String str = sc.next();


這段代碼只能獲取一個單詞,但您打算獲取n單詞。


您可以擺脫數組,因為它是不必要的,然后使用:


        for(int i=0;i<n;i++){

            String word = sc.next();

            if(wordCount.containsKey(word)){

                wordCount.put(word,wordCount.get(word)+1));

            }

            else{

                 wordCount.put(word,1);

            }

        }

但是,更簡潔的寫法是:


for(int i=0;i<n;i++){

    wordCount.compute(sc.next(), (word,count)-> (count==null)? 1 : count+1);

}


查看完整回答
反對 回復 2021-08-25
?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

我認為

for(int i=0;i<n;i++){

應該:

for(int i=0; i < strArray.length; i++) {


查看完整回答
反對 回復 2021-08-25
  • 2 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號