Java - replace() method using values from arrays is changing the array values?

半世苍凉 提交于 2019-12-02 20:14:05

问题


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.


回答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.



来源:https://stackoverflow.com/questions/35670550/java-replace-method-using-values-from-arrays-is-changing-the-array-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!