简体   繁体   中英

How do you solve this problem with a nested for loop

My goal is to print out names with 2 letters that are the same with only one of the same letter in the name. For example brook would be printed out as brok and michelle would be printed out as michel. Whats wrong with my code?

   for(int a = 0; a < word_1.length(); a++)
         {
              mychar = word_1.charAt(a);
               for(int c = 1; c <word_1.length(); c++)
                 {
                    mychar_2 = word_1.charAt(c);
                      if(mychar == mychar_2)
                      {
                           word_3 = word_3 + "";
                       }
                       else 
                         {
                             word_3 = word_3 + mychar;
                         }
                     }
         }
  System.out.println(word_3);

Better question is "what is right with the code". Basically the idea looks like going through all letters and then going through all matches. This is not too bad and we can slightly change your code to make it work (see comments):

for(int a = 0; a < word_1.length(); a++)
{
    char mychar = word_1.charAt(a);

    // flag for matching letters
    Boolean found = false;

    // you go through only previous characters!
    for(int c = 0; !found && c < a; c++)
    {
        char mychar_2 = word_1.charAt(c);
        if(mychar == mychar_2)
        {
            found = true;
        }
    }

    // here you add character if no match found
    if(!found) {
        word_3 = word_3 + mychar;
    }
}

This is a good way in academic coding, but in actual project if you deal with large numbers of words, you have to consider Map based solution to keep all existing letters and iterate only once through each word. Or you can search for some methods in numerous java libraries to do the job

This would solve the problem:

        String testWord = "brook";
        List<String> testSet = new ArrayList<String>();
        for (int i = 0; i < testWord.length(); i++) {
            if (!testSet.contains(String.valueOf(testWord.charAt(i)))) {
                testSet.add(String.valueOf(testWord.charAt(i)));
            }
        }
        StringBuilder builder = new StringBuilder();
        for (Object s : testSet.toArray()) {
            builder.append((String) s);
        }
        String str = builder.toString();
        System.out.println(str);

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