java - 如何将所有这些索引放入 char 数组?
问题描述
我找不到将 encryptedChar 放入 char 数组的方法,以便我可以将消息放在一行中。如果有人能给我一个简单的问题解决方案或以任何方式帮助我,那就太好了!
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// can get the index without key. DONE
// encrypt message. finish equation.
int encryptKey, encryptedIndex;
int plainLetterIndex = 0;
int loadingBar = 3;
char encryptedChar;
char[] alphaArray = {'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'};
String redo, message;
System.out.println("Welcome to the encrypter and decrypter program. The program will take the message");
System.out.println("and either encrypt it or decrypt it. Depending on what you choose to do.");
System.out.println("");
do {
System.out.println("Please enter your message!");
message = sc.nextLine();
message = message.toUpperCase();
System.out.print("Would you like to re-enter your message? (Y/N)");
redo = sc.nextLine();
} while (redo.equals("Y") || redo.equals("y"));
// declaring arrays
char[] messageArray = message.toCharArray();
char[] encryptedMessageArray = new char[messageArray.length];
// asking for key
System.out.println("Please input the 'key' you would like to use to encrypt your message.");
while(true){
try{
encryptKey = Integer.parseInt(sc.nextLine());
break;
} catch (NumberFormatException ignore){
System.out.println("You have entered an incorrect number, please try again!");
}
}
System.out.println(" ");
for (int i = 0; i < messageArray.length; i++) {
//System.out.println(messageArray[i]);
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
//encryptedMessageArray = encryptedChar;
System.out.print(encryptedChar);
}
}
}
sc.close();
}
}
解决方案
使用索引变量encryptedMessageArray
,每次将字符放入时增加它encryptedMessageArray
int index = 0;
for (int i = 0; i < messageArray.length; i++) {
//System.out.println(messageArray[i]);
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[index] = encryptedChar;
index++;
}
}
}
System.out.println();
System.out.println(encryptedMessageArray);
推荐阅读
- javascript - 将多个选中复选框的值传递到多个相应的输入字段
- python - 我无法在 Matplotlib 中同时获得多个实时绘图 - Python
- jboss - 什么时候在 Oracle ATG 中创建 Jsession id 是来自 JBOSS 还是 ATG?
- firebase - Google ML Engine 在线预测请求没有响应预测结果
- javascript - 如何在 ng-show 和 ng-hide 上应用水平滑动动画?
- php - WordPress is_single 执行此操作,如果不是特定的单个 ID 执行此操作
- sqlite - 使用子组限制创建行组
- akka - InputStream 在图形运行中关闭
- python - 在数据框单元格中添加设置值
- php - codeigniter - 内部连接错误