我的代码有问题。我创建代码来做两件事:加密文本和解密文本。我的代码是正确加密但Decrypt方法不起作用。我做了一些更改以纠正Decrypt方法,但结果是加密和解密都不起作用。我试着纠正它,但我不能。帮助我纠正方法并使其正确。
头等舱
package so4717814;
public class text {
public static final int AlphaSize = 26;
public static final char[] alpha = { //
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', //
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', //
};
protected char[] encrypt = new char[AlphaSize];
protected char[] decrypt = new char[AlphaSize];
public text() {
for (int i = 0; i < AlphaSize; i++)
encrypt[i] = alpha[(i + 3) % AlphaSize];
for (int i = 0; i < AlphaSize; i++)
decrypt[encrypt[i] - 'a'] = alpha[i];
}
public String Encryption(String secret) {
char[] mess = secret.toCharArray();
for (int i = 0; i < mess.length; i++)
if (Character.isUpperCase(mess[i]))
mess[i] = encrypt[mess[i] - 'a'];
return new String(mess);
}
public String decryption(String secret) {
char[] mess = secret.toCharArray();
for (int i = 0; i < mess.length; i++)
if (Character.isUpperCase(mess[i]))
mess[i] = decrypt[mess[i] - 'a'];
return new String(mess);
}
}
第二课
package so4717814;
import java.util.Scanner;
public class TextApp {
public static void main(String[] args) {
text T1 = new text();
System.out.println();
System.out.print("\n ~WELCOME~\n");
Scanner scanner = new Scanner(System.in);
System.out.printf("\nPlease choose one:\n\n1-%s\n\n2-%s\n", "Encrypt Message", "Decrypt message");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("\nEnter your Message :\n ");
String secret = scanner.next();
System.out.printf("\n The Encryption is :\n");
secret = T1.Encryption(secret);
System.out.println();
System.out.println(secret);
System.out.println();
break;
case 2:
System.out.println("\nEnter your message :\n ");
String message = scanner.next();
System.out.printf("\n The Decryption is :\n");
message = T1.decryption(message);
System.out.println();
System.out.println(message);
System.out.println();
break;
}
System.out.println("\n\tThank you for useing my program\t\n\t\t ;)\n\n");
}
}
答案 0 :(得分:1)
我认为没有任何改变的原因是你的加密循环只将加密转换应用于大写字母。如果值是小写字母,数字,标点符号等,则永远不会更改乱码数组中的字符。要解决此问题,请尝试更改加密逻辑以处理所有类型的字符,而不仅仅是大写字符。