爪哇 - 替换()利用数组值的方法是改变数组值? [英] Java - replace() method using values from arrays is changing the array values?

查看:170
本文介绍了爪哇 - 替换()利用数组值的方法是改变数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做类似

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;
}

当然这被简化,真正的code我用采用全字母和一些数字。因此,这里是我的问题:如果我输入类似 123 加密()并输出 NGV 然后我输入 NGV 成解密()它给了我像 1q3 。只有一些字母都正确切换,有些则不是。是不是有什么用替换()使用方法我失踪数组值?我显然对Java。

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.

此外,我读 Java的替代()的问题,但的replaceAll()没有工作了。

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

推荐答案

我怀疑你的问题是为什么链接 .replace 奇怪演戏,阵列没有改变。你能证明代替不会很容易改变数组:

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));

这是怎么回事与您的code?每次更换你结束了一个新的字符串的信,一遍你替换字母。我没有完整的源代码code,所以我会用一个真正简单的版本显示:

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");

有关ABC是......DDD。

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.

这篇关于爪哇 - 替换()利用数组值的方法是改变数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆