0

I'm doing something like

public static String[] list = {"a","b","c","d",}  //It gives me a NullPointeException if I didn't use static
public String encrypt(String a){
   a = a.replace(list[0],list[2]);
   a = a.replace(list[4],list[3]);
   return a;
}

and I have another method that just reverses it

public String decrypt(String a){
   a = a.replace(list[2],list[0]);
   a = a.replace(list[3],list[4]);
   return a;
}

Of course this is simplified, the real code I'm using uses the entire alphabet and some numbers. So here's my problem: If I input something like 123 into encrypt() and it outputs ngV then I input ngV into decrypt() it gives me like 1q3. Only some of the letters are correctly switched and some aren't. Is there something with the replace() method using array values that I'm missing? I'm obviously new to Java.

Also I read Java replace() problems but replaceAll() didn't work out.

Community
  • 1
  • 1
Michael Chen
  • 21
  • 2
  • 5
  • Strings are immutable, so you need to store the result of `a.replace(...);` – Tunaki Feb 27 '16 at 13:47
  • "If I input something like 123 into encrypt() and it outputs ngV" That's never going to happen. – Joni Feb 27 '16 at 13:52
  • I'm very sorry guys, I edited my code again. I had a = a.replace(); So Tunaki are you suggesting that I store the result of a.replace. However, the problem is still the same, Do you want a video of me demonstrating it? – Michael Chen Feb 28 '16 at 06:09
  • @MichaelChen Use the "@" before the user's name to send him a notification. – Maroun Mar 03 '16 at 16:01
  • 3
    Please provide a full example. The code posted above does not work: The array cannot be assigned like that and ``list[4]`` does not exist. Break down the problem into your own small sample program and post it here. – f1sh Mar 03 '16 at 16:06
  • Put some `System.out.println(a)` after each replace (or use a debugger). – Michael Lloyd Lee mlk Mar 03 '16 at 16:06

1 Answers1

1

I suspect your question is "why is chaining .replace acting oddly" and the array is not changing. You can prove that replace does not change the array quite easily:

    System.out.println(Arrays.toString(list));
    encrypt("abc");
    System.out.println(Arrays.toString(list));

So what is going on with your code? Each time you replace a letter you end up with a new string, that again you replace letters on. I don't have your full source code so I'll show with a real simple version:

a = a.replace("a", "b");
a = a.replace("b", "c");
a = a.replace("c", "d");

For "abc" is.... 'ddd'.

The answer to this is to look at each letter at a time and change it. Loop through the string and create a new one.

Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81