我试图将我的字符串放入列而不使用数组加密但不知道如何继续而不使用数组请帮助:
我需要让他们这样:
3 1 2
S E L
L A L
L S T
O C K
S N O
W
样本输出:
生成密钥:213
输入您要编码的秘密消息:立即售出所有股票
加密消息:EASCNSLLOSWLLTKO
我目前的代码:
int num1 = (int) (1+ Math.random() * 3);
int num2 = (int) (1+ Math.random() * 3);
int num3 = (int) (1+ Math.random() * 3);
while (num1 == num2 || num2 == num3 || num1 ==num3) {
num2 = (int) (1+ Math.random() * 3);
num3 = (int) (1+ Math.random() * 3);
}
String key = num1 + "" + num2 + "" + num3 + "";
System.out.println("Generated key: " + key);
System.out.println("Enter a secret message you wish to encode: ");
String message = input.nextLine();
String withoutspace = message.replaceAll("\\s", "");
String capitalMessage = withoutspace.toUpperCase();
基本上我可以通过这样做得到column1:
String row = cap.charAt(0) + "" + cap.charAt(3) + "" + cap.charAt(6)+ "" + cap.charAt(9) +"" + cap.charAt(12)+"" + cap.charAt(15)+"";
但我需要为每一列做一个循环,以获得每个第三个字母,无论这个单词有多长。
//Initiation of variables
String string1 = "";
String string2 = "";
String string3 = "";
//loop for first string
for (int i = 0; i < cap.length(); i+=3){
string1 += (cap.charAt(i) + "");
}
//loop for second string
for (int j = 1; j < cap.length(); j+=3){
string2 +=(cap.charAt(j) + "");
}
//loop for third string
for (int k = 2; k < cap.length(); k+=3) {
string3 +=(cap.charAt(k) + "");
}
//Prints out the encrypted message based on which key is given
if(key.equals("123")) {
System.out.println("Encrypted message: " + string1 + string2 + string3);
}else if(key.equals("132")) {
System.out.println("Encrypted message: " + string1 + string3 + string2);
}else if(key.equals("213")) {
System.out.println("Encrypted message: " + string2 + string1 + string3);
}else if(key.equals("231")) {
System.out.println("Encrypted message: " + string2 + string3 + string1);
}else if(key.equals("312")) {
System.out.println("Encrypted message: " + string3 + string1 + string2);
}else {
System.out.println("Encrypted message: " + string3 + string2 + string1);
}