猿问

遍历哈希图时数组索引越界异常

我正在尝试编写一个 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--;


        }

    }

}


Cats萌萌
浏览 162回答 2
2回答

梦里花落0921

String str = sc.next();这段代码只能获取一个单词,但您打算获取n单词。您可以摆脱数组,因为它是不必要的,然后使用:&nbsp; &nbsp; &nbsp; &nbsp; for(int i=0;i<n;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String word = sc.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(wordCount.containsKey(word)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wordCount.put(word,wordCount.get(word)+1));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;wordCount.put(word,1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }但是,更简洁的写法是:for(int i=0;i<n;i++){&nbsp; &nbsp; wordCount.compute(sc.next(), (word,count)-> (count==null)? 1 : count+1);}

摇曳的蔷薇

我认为for(int&nbsp;i=0;i<n;i++){应该:for(int&nbsp;i=0;&nbsp;i&nbsp;<&nbsp;strArray.length;&nbsp;i++)&nbsp;{
随时随地看视频慕课网APP

相关分类

Java
我要回答