Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
字符串替换isn';t在for loop-Java中工作_Java_Random_Char - Fatal编程技术网

字符串替换isn';t在for loop-Java中工作

字符串替换isn';t在for loop-Java中工作,java,random,char,Java,Random,Char,由于某些原因,此代码不起作用 public void actionPerformed(ActionEvent e) { Random random = new Random(); int randomChar = random.nextInt((23 - 0) + 1); for(int x = 23;x > 0;x-- ) { String text;

由于某些原因,此代码不起作用

public void actionPerformed(ActionEvent e) {

            Random random = new Random();
            int randomChar = random.nextInt((23 - 0) + 1);
            for(int x = 23;x > 0;x-- ) {

                String text;
                text = original.getText();
                text = text.toLowerCase();
                text = text.replace(alphabet[x], alphabet[randomChar]);

                newText.setText(text);

            }
text = text.replace(alphabet[x], alphabet[randomChar]);
只需要澄清一下,original和newText是JTextField,alphabet是一个带有a-z的字符数组

text = text.replace(alphabet[x], alphabet[randomChar]);
现在,当我运行这个程序时,它应该遍历并用一个随机字符替换每个字符,从Z开始,到a结束,但是它给我的字符串与我输入的字符串完全相同,只是转换成小写

text = text.replace(alphabet[x], alphabet[randomChar]);
值得注意的是,如果我更换

text = text.replace(alphabet[x], alphabet[randomChar]);

text = text.replace(alphabet[x], alphabet[randomChar]);
在输入框里放一堆a,它会把它们变成一个随机的字母。例如:

text = text.replace(alphabet[x], alphabet[randomChar]);
aaaa input
llll output
or gggg output
如果我有一个变量在里面,它就不起作用了

text = text.replace(alphabet[x], alphabet[randomChar]);
顺便说一下,代码的其余部分并不重要,它们都是声明变量和设置GUI

text = text.replace(alphabet[x], alphabet[randomChar]);

非常感谢您的帮助

在循环之前用一些字符设置randomchar,然后将所有字符替换为所述字符,因此“yourstring”变成“xxxxxxxxx”,其中x=randomchar

除了在循环中移动随机字符生成(如@cisforcoockies所建议的),还需要移动
getText()
setText()
在循环外调用(因为每次循环运行时,您都会以原始的文本重新开始,因此无论循环重复多少次,最后最多只能替换一种字符。

除了另外两个答案之外,我想在for循环中添加一条注释:

text = text.replace(alphabet[x], alphabet[randomChar]);
for(int x = 23;x > 0;x--)
当x==0时,您根本不会进入循环,这意味着字母表数组中的第一个字符不会被考虑替换

text = text.replace(alphabet[x], alphabet[randomChar]);

如果你已经有了字母数组,想用随机的来替换每个字符,为什么不考虑使用:

text = text.replace(alphabet[x], alphabet[randomChar]);
for (int x = 0; x < alphabet.length; x++){
  //your code here
}
for(int x=0;x

这应该比硬编码更好

尝试在循环中打印随机字符和输入的字符串,这样您就可以调试正在发生的事情,并确保字符串实际包含字符。两者都工作正常,X在递减,random在拾取随机数(我将其移动到for循环中后,顺便说一句,这并没有解决问题)谢谢,我真不敢相信我忽略了这一点。
text = text.replace(alphabet[x], alphabet[randomChar]);