Your solution came close to working. You just need to consider occurrences with more than 1
and disregard letters that have already been processed. There are many possibilities to solve the already processed letters, and one of them would be to store in a String
apart from which have already left and do not consider these.
Keeping your original logic and making these adjustments would look like this:
char Char;
int count;
String s = "Par programming is fun!";
s = s.toLowerCase();
String carateresSaidos = ""; //para manter registo das letras que ja sairam
for (Char = 0; Char <= s.length()-1; Char++) {
count = 0;
if (carateresSaidos.indexOf(s.charAt(Char)) == -1){ //se ainda não saiu
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(Char)) {
count++;
}
}
if (count > 1){ //mostra apenas se é repetida, ou seja, se há mais que uma
System.out.println("Number of occurences of "+s.charAt(Char) + " is " + count);
}
carateresSaidos += s.charAt(Char); //adicionar esta letra as que já sairam
}
}
Example in Ideone
However, there are much more performative solutions, which do not require using two for
(which is a quadratic solution). I show you a solution, equated to @Felipe’s latest solution, but using a native array to count multiple letters. This solution assumes that the String
contains only ASCII characters.
int[] contagens = new int[256];
for (int i = 0; i < s.length(); ++i)
contagens[s.charAt(i)]++;
for (int i = 0; i < 256; ++i){
if(contagens[i] > 1){
System.out.println("Number of occurences of " + (char)i + " is " + contagens[i]);
}
}
See this solution also in Ideone
The first for
passes in each letter and increases 1
position corresponds in the array. The position will correspond to the letter number in the ASCII table. The second for
just shows the scores that got more than 1
.
No, use Processing which is a java subset.
– find83