简体   繁体   中英

Can someone help me correct this java loop. It's so close to being right

So I have an ArrayList called originalList that looks like the following:

[pans, naps, pots, sit, it's, tis, snap]

I also have an ArrayList called modifiedList which looks like

[anps, anps, opst, ist, ist, ist, anps]

Modified list takes the original list, removes punctuation, and sorts it. The purpose of this program is to take an input ( originalList ) and see if there are anagrams in the input. An anagram are words that consist of the same letters. I am getting a problem with my loop which prints out the anagrams. Here's the loop:

    for (int i=0; i<modifiedList.size();i++){
        System.out.print(originalList.get(i));
        for (int j=i+1;j<modifiedList.size();j++){
            if (modifiedList.get(i).contentEquals(modifiedList.get(j))){
                System.out.print(" "+ originalList.get(j));
                originalList.remove(j);
                modifiedList.remove(j);                     
            }

        }System.out.println();

    }

when I run the loop I get the following:

pans naps snap
pots
sit it's
tis

Everything is correct except tis is not listed as an anagram of sit and it's. This is the cause of using modifiedList.remove(j) which causes the second loop to exit before it gets to tis, and tis is never printed with sit and it's. modifiedList.remove(j) is necessary so that words are not repeated in the output. How would I fix this so that tis is listed as an anagram of sit and it's?

The problem is that you are changing the indexing on the array, but not changing j. When you remove, you reduce the index of every following item by 1. So, when you hit it's, it matches. You remove it's, moving tis to the index it's used to have. Then, you add 1 to j, which now runs off the end of the array (because snap was already removed). So, after removing j, you need to decrement j by 1.

Reverse your loops -- work from the back of the array to the front. That way, when you remove an entry, you don't change the index of the entries you haven't read yet.

Your other option is to take into account the removal by adjusting your loop indices, but that's trickier.

(And yet another option is to make up an object that contains the original string and the sorted string. Make an array of these, and sort it using a sort scheme that will sort on the sorted string. Then scan through the list and note when you have a "run" of identical sorted keys. No removal required.

A "cheater" way to create that object is to just have the sorted and original strings together in one string, separated by a space or some other special character, then sort the strings.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM