I have been asked to write a class that encodes a given sentence using specific rules. This class should use loops and Stringbuffer
. The rules are:
I have written the code, but I am not able to understand why it is not working. Can anyone help?
For example:
sentence = "Katie likes to observe nature."
It should be transformed to:
"Kaie iks t obere ntue*8"
However, using my code I get: "Katie likes to observe nature*."
Thank you!
public void createEncodedSentence() {
StringBuffer buff = new StringBuffer();
int counter = 0;
char a;
for (int i = 0; i < sentence.length(); i++) {
a = sentence.charAt(i);
if (a == '.') {
buff.append('*');
}
if (a != ' ' && a != '.') {
counter++;
}
if (counter % 3 == 0) {
buff.append("");
}
buff.append(sentence.charAt(i));
}
encodedSentence = buff.toString();
}
The main issue with your logic is that after you append a String to buff
you continue with that iteration instead of jumping to the next character in the String.
Change your method to as follows :
public static StringBuffer createEncodedSentence(String sentence) {
StringBuffer buff = new StringBuffer();
int counter = 0;
char a;
for (int i = 0; i < sentence.length(); i++) {
a = sentence.charAt(i);
if (a == '.') {
buff.append("*");
continue;
}
if ((i + 1) % 3 == 0 && a != ' ' && a != '.') {
counter++;
continue;
}
buff.append(sentence.charAt(i));
}
buff.append(counter);
return buff;
}
Logic:
.
then we append a *
and jump to the next character in the sentence.