I am trying to do a project for my computer science class called "Encryption/Decryption"
The code goes as 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 a sentence that is to be 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 the Tester class, it's in the Crypto class.
The input is: This is a very big morning.
And the code should output:
Enter a sentence that is to be encrypted: This is a very big morning.
Original Sentence: This is a very big morning.
Encrypted sentence: This is a ag',rery dug>?/ijeb..w ssadorninjeb..w.
Decrypted sentence: This is a very big morning.
But instead the Encrypted sentence line is printing:
This is a ag',rery dujeb..w>?/ijeb..w ssadorninjeb..w.
The sntnc.replace method is replacing the already replaced letters.
How do I fix it to where it won't replace things twice?
replaceAllis for regular expressions. Are you using regular expressions? If not (or if you don't know) you probably want to usereplaceinstead.replaceAll. I was just messing around and seeing if that would fix it. But even withreplaceit still doesn't work.