I have little problem with my code, I split in Java String to table, then for I pick selected char and replace it with StringBuffer method. The problem is when I use sout method at the end with extracted toString(), my ciphered value is automatically displayed with raw value that at the beginning I wanted to cipher. I tried a lot with clearing BufferedStream but can not disattach it. See also picture below code enter image description here
public class third {
public static void main(String[] args) {
String letter = "drukarka";
String[] tab1 = letter.split("");
String result = "Result of cypher: ";
StringBuffer cypher = new StringBuffer("drukarka");
for (int i = 0; i < tab1.length; i++) {
String word = tab1[i];
int k = tab1.length;
k--;
if (word.equals("d")) {
cypher.replace(Integer.valueOf(tab1.length-k-1), Integer.valueOf(tab1.length-k-1), "#");
} else if (word.equals("r")) {
cypher.replace(Integer.valueOf(tab1.length-k-1), Integer.valueOf(tab1.length-k-1), "!");
} else if (word.equals("u")) {
cypher.replace(Integer.valueOf(tab1.length-k-1), Integer.valueOf(tab1.length-k-1), "$");
} else if (word.equals("k")) {
cypher.replace(Integer.valueOf(tab1.length-k-1), Integer.valueOf(tab1.length-k-1), "&");
} else if (word.equals("a")) {
cypher.replace(Integer.valueOf(tab1.length-k-1), Integer.valueOf(tab1.length-k-1), ";");
}
}
String[] cypher2 = cypher.toString().split("");
StringBuffer cypher3 = new StringBuffer("");
for (int i = 0; i < cypher2.length; i++) {
cypher3.append(cypher2[i]);
}
String cyphered = String.valueOf(cypher3);
cypher.setLength(0);
cypher3.setLength(0 );
thirdd construction = new thirdd();
construction.constructor(letter, result, cyphered);
System.out.println(construction.toString());
}
}
Your code is rather weird. You want to replace the letters in
cypher, but you aren't replacing them. Instead it looks like you are always inserting the replacements at the very end of the string.I think you want something like this (not tested)
Or an even simpler version: