所以我做了這個任務,最後我轉過來了,但在我的心裏,我覺得我沒有正確編寫程序。它在吃我,我真的想明白我做錯了什麼。所以這裏是代理人:我錯過了什麼使它成爲一個簡單的替代密碼來加密和解密消息?
編寫一個程序,可以使用 任意替換密碼進行加密和解密。在這種情況下,加密陣列是所有可打印ASCII字符(包括 字符:空格)的隨機混排 。
還包括了一個洗牌的想法:
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Character[] original = new Character[]{'A', 'B', 'C', 'D', 'E'};
Character[] encrypted = new Character[]{'A', 'B', 'C', 'D', 'E'};
Collections.shuffle(Arrays.asList(encrypted));
System.out.println(Arrays.toString(encrypted));
}
}
,這就是我想出了:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Caesar {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter anything: ");
String input = keyboard.nextLine();
char[] original = input.toCharArray();
char[] encrypted = input.toCharArray();
String a = new String(original);
// Ask if we would like to encrypt
System.out.print("Shall we encrypt? (Y/N): ");
char selection = keyboard.next().charAt(0);
selection = Character.toUpperCase(selection);
if (selection == 'Y') {
// Encryption process
shuffleArray(encrypted);
System.out.print("Encrypted message: ");
for (int i = 0; i < encrypted.length; i++) {
System.out.print(encrypted[i]);
}
System.out.println();
System.out.print("Shall we decrypt? Y/N: ");
selection = keyboard.next().charAt(0);
selection = Character.toUpperCase(selection);
if (selection == 'Y') {
System.out.println("Decrypted message: " + a);
}
} else if (selection == 'N') {
System.out.print("Nothing was done to the text: " + a);
} else {
System.out.println("You must enter either Y or N!");
}
}
static void shuffleArray(char[] ar) {
Random random = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
// Simple swap
char a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
它開始作爲一個愷撒密碼,但我厭倦了和最後簡單地使用隨機洗牌,問題是加密僅適用於該實例。我希望能夠可靠地解密消息,即使在其間發生其他實例。我幾乎可以在腦海中看到解決方案,但這只是遙不可及。任何人都可以幫我連接點嗎?