Java 如何覆盖循环中的字符串 public静态字符串解密(final String encryptedText,final int n){ 字符[]字符; 字符串s=encryptedText; 字符串s1=“”; int缓冲区=0; int buffer2=1; 对于(int j=0;j
存在一些其他问题:Java 如何覆盖循环中的字符串 public静态字符串解密(final String encryptedText,final int n){ 字符[]字符; 字符串s=encryptedText; 字符串s1=“”; int缓冲区=0; int buffer2=1; 对于(int j=0;j,java,string,Java,String,存在一些其他问题: ArrayIndexOutOfBoundsException,因为在最后一个循环中的条件缓冲区是什么意思?S应该是charsUpdate的串联。如果使用'String S=新字符串(charsUpdate)更容易些“由于在if语句中重新读取chars=s1.toCharArray(),因此在第一次迭代后会得到空字符串和s1是一个空字符串我更改了代码,但仍然不工作您可能需要在更新中检查重构/改进的版本。工作正常,是的,我昨天检查了,并结束了我的任务,非常感谢 public
ArrayIndexOutOfBoundsException
,因为在最后一个循环中的条件缓冲区是什么意思?S应该是charsUpdate的串联。如果使用'String S=新字符串(charsUpdate)更容易些“由于在if
语句中重新读取chars=s1.toCharArray(),因此在第一次迭代后会得到空字符串
和s1
是一个空字符串我更改了代码,但仍然不工作您可能需要在更新中检查重构/改进的版本。工作正常,是的,我昨天检查了,并结束了我的任务,非常感谢
public static String decrypt(final String encryptedText, final int n) {
char [] chars;
String s = encryptedText;
String s1 = "";
int buffer = 0;
int buffer2 = 1;
for (int j = 0; j < n; j++) {
if (j < 1){
chars = s.toCharArray();
}else{
chars = s1.toCharArray();
}
char [] charsUpdate = new char[chars.length];
for (int i = chars.length / 2; i < chars.length; i++) {
if (buffer % 2 == 0 && buffer <= charsUpdate.length){
charsUpdate[buffer] = chars[i];
}
buffer += 2;
}
for (int i = 0; i < chars.length / 2 ; i++) {
if (buffer2 % 2 != 0 && buffer2 < charsUpdate.length){
charsUpdate[buffer2] = chars[i];
}
buffer2 += 2;
}
s = "";
s1 = "";
for (int i = 0; i < charsUpdate.length; i++) {
s = s + charsUpdate[i];
}
s1 = s;
}
return s;
public static String decrypt(final String encryptedText, final int n) {
int len = encryptedText.length();
int half = len / 2;
String s = encryptedText;
for (int j = 0; j < n; j++) {
char[] chars = s.toCharArray();
char[] charsUpdate = new char[len];
for (int i = half, even = 0; i < len && even < len; i++, even += 2) {
charsUpdate[even] = chars[i];
}
for (int i = 0, odd = 1; i < half && odd < len; i++, odd += 2) {
charsUpdate[odd] = chars[i];
}
s = new String(charsUpdate);
}
return s;
}
for (int i = 1; i < 5; i++) {
System.out.println("abcdefgh (" + i + ") -> " + decrypt("abcdefgh", i));
}
abcdefgh (1) -> eafbgchd
abcdefgh (2) -> gecahfdb
abcdefgh (3) -> hgfedcba
abcdefgh (4) -> dhcgbfae
----
// for odd length of the input string
abcdefg (1) -> daebfcg
abcdefg (2) -> bdfaceg
abcdefg (3) -> abcdefg
abcdefg (4) -> daebfcg