使用你已经实现的,我做了一个加密方法。我还添加一个解密方法:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.printf("Please enter a string: ");
String message = input.nextLine();
String encryptedMessage = encrypt(message);
System.out.println(encryptedMessage);
System.out.println(decrypt(encryptedMessage));
input.close();
}
public static String encrypt(String message) {
String encrypted = "";
int i = 0;
int length = message.length();
while (i < length) {
int ascii = message.charAt(i++);
encrypted += " " + ascii;
}
return encrypted.trim();
}
private static String decrypt(String encryptedMessage) {
Scanner scanner = new Scanner(encryptedMessage);
String decryptedMessage = "";
while(scanner.hasNext()) {
decryptedMessage += (char) scanner.nextInt();
}
scanner.close();
return decryptedMessage;
}
挑战
在上面的代码中,经加密的消息在每个整数集,它表示一个字符之间的空间。看一眼加密的消息,很容易发现你只是将每个字符转换为与ASCII等价的字符。
代替的空间中,尝试插入ASCII码之间的非数字字符。然后,在解密方法中,使用Scanner#useDelimiter
指定该字符以检索ASCII值。
'length'决不会小于或等于'长度1' ;-) – janos
有道理。那么除此之外的其他条件是否所有其他条件都看起来不错? – user2874910