string - Java replace method problems -
i trying project computer science class called "encryption/decryption"
the code goes follows
import java.io.*; import java.util.*; import java.io.*; import java.util.*; public class tester { public static void main(string args[]) { scanner kbreader = new scanner(system.in); system.out.print("enter sentence encrypted: "); string sntnc = kbreader.nextline(); system.out.println("original sentence = " + sntnc); crypto mycryptobj = new crypto(); string encryptdsntnc = mycryptobj.encrypt(sntnc); system.out.println("encrypted sentence = " + encryptdsntnc); string decryptdsntnc = mycryptobj.decrypt(encryptdsntnc); system.out.println("decrypted sentence = " + decryptdsntnc); } } class crypto { public string encrypt(string sntnc) { sntnc = sntnc.replace("m", "ssad"); sntnc = sntnc.replace("b", "dug>?/"); sntnc = sntnc.replace("g", "jeb..w"); sntnc = sntnc.replace("v", "ag',r"); return sntnc; } public string decrypt(string sntnc) { sntnc = sntnc.replace("ag',r", "v"); sntnc = sntnc.replace("ssad", "m"); sntnc = sntnc.replace("jeb..w", "g"); sntnc = sntnc.replace("dug>?/", "b"); return sntnc; } } the problem isn't in tester class, it's in crypto class.
the input is: this big morning. , code should output:
enter sentence encrypted: big morning. original sentence: big morning. encrypted sentence: ag',rery dug>?/ijeb..w ssadorninjeb..w. decrypted sentence: big morning. but instead encrypted sentence line printing:
this ag',rery dujeb..w>?/ijeb..w ssadorninjeb..w. the sntnc.replace method replacing replaced letters. how fix won't replace things twice?
the problem comes logic of replacing strings:
sntnc = sntnc.replaceall("b", "dug>?/"); // <-- replaces "g" here sntnc = sntnc.replaceall("g", "jeb..w"); // <-- "g" getting replaced here a simple solution drop using replaceall. making code works re-ordering replaceall calls fragile: don't know in future change getting replaced , break everything.
the solution simpler when building string iterating on characters. because have distinct temporary container when building strings, there no conflicts when replacements happening.
public string encrypt(string sntnc) { stringbuilder sb = new stringbuilder(); (char ch : sntnc.tochararray()) { if (ch == 'm') sb.append("ssad"); else if (ch == 'b') sb.append("dug>?/"); else if (ch == 'g') sb.append("jeb..w"); else if (ch == 'v') sb.append("ag',r"); else sb.append(ch); } return sb.tostring(); }
Comments
Post a Comment