replace() will return a new String where ALL occurrences of a particular character are changed, not just a character at a particular position. So your problem is that the repeated replace() statements are effectively modifying the values back and forth.
Because a String is immutable, you cannot simply replace its characters with others dynamically. So, convert your code to use a StringBuilder instead.
StringBuilder buildSample = new StringBuilder();
buildSample.append(sample);
Now you can use setCharAt() instead of replace() to change the character at one position at a time.
buildSample.setCharAt(i, 'A');
At the end, you can return buildSample.toString().
As for changing each letter A to F to its complement, if only these six letters are required, a hard-coded function with a switch statement would do. Otherwise you can use a function like complementaryLetter() below, which returns the complement after checking the ASCII value of the character. This will work for all characters. You can add code to handle invalid cases, for non-character input.
A complete working code:
public class Replace {
public static void main(String[] args) {
String s1 = "ABCDEFA";
System.out.println(s1);
s1 = changeSample(s1);
System.out.println(s1);
}
public static char complementaryLetter(char letter) {
char retChar = 'A';
if ((int) letter % 2 == 0)
retChar = (char) ((int)letter - 1);
else
retChar = (char) ((int) letter + 1);
return retChar;
}
public static String changeSample(String sample) {
StringBuilder buildSample = new StringBuilder();
buildSample.append(sample);
for (int i = 0; i < sample.length(); i++) {
buildSample.setCharAt(i, complementaryLetter(sample.charAt(i)));
}
return buildSample.toString();
}
}
i++ori=i+1?ifstatements. However, he'll have an endless loop if the character isn't handled.replacemethod that it will replace all occurrences of character in the string.