Here I did a puzzle, but for some reason it does not work, help, please, to make out the mistakes.

The meaning of the task is to find characters in the string that occur 1 time.

package org.jazzteam; public class ArbitrarySymbols { public static String one() { String l = ""; String str = "hello Wrold"; int count = 0; int count1 = 0; char chars[] = str.toCharArray(); for (int i = 0; i < str.length(); i++) { for (int j = 0; j < str.length(); j++) { if (chars[i] == chars[j]) { count++; } } if (count > 1) { } else { l += str.charAt(i); count = 0; } } return l; } public static void main(String[] args) { System.out.println(one()); } } 
  • @Wengelm; To format a code, select it with the mouse and click on the button 101010 of the editor. - Nicolas Chabanovsky
  • one
    is it that opened a set of courses? a couple of days ago the exact same task was - Gorets
  • There is no set :) - Wengelm

2 answers 2

 public static String one() { String l = ""; String str = "hello World"; int count = 0; char chars[] = str.toCharArray(); for (int i = 0; i < str.length(); i++){ for (int j = 0; j < str.length(); j++){ if (chars[i] == chars[j] && i != j){ count++; } } if (count < 1){ l += str.charAt(i); } else { count = 0; } } return l; } 
  • those. I had an error in that I did not return the value of 0 to the counter and did not check the additional condition when i was not equal to j? I'm just learning java myself. Thanks for the help! - Wengelm

Make an array of counters about the size of the power of your characters. (simple - Russian 'I' has a decimal code 1103 so take to your taste, say 2048).

Initialize it with zeros. You browse the string once (!), Using the character as an index in the array of counters, increment the counter.

At the end, run through the array of counters and output those indices (like characters) for which the counter is 1.

And no nested loops in similar tasks.

  • count, once the form of such an implementation, there was a class in the code in which there was an alphabet and in it there was a number for each letter, then it was compared here and there, in short, it was PPC =) - Gorets
  • The author is just starting to learn, so I did not offer him HashMap (), but warned against a fundamentally bad (in general) algorithm. - avp
  • Well, then you don’t need advice about 2048. Suddenly, he wants to write in Georgian? Or in some tricky language. The truth in ucs-2 is just maybe 2 ^ 16 characters. - alexlz
  • @alexlz, do you think that the algorithm used by the author is normal ? - avp
  • one
    Well no. I just do not think HashMap is so scary to scare newbies. Schoolchildren use php, and there are no reports of work injuries - alexlz