[英]Taking string with whitespaces, splitting it into individual characters, and adding it to a char list
好的,所以我試圖在Java中創建一個Caesar密碼,並且嘗試使用以前使用的python方法,在此方法中,您將接收用戶輸入並檢查主字符串'alphabet中是否存在任何字母',然后使用移位值查找字符的當前索引,然后向其添加移位值,然后將該當前字符添加至新字符串'EncryptedMessage'。
我似乎無法弄清楚如何轉換用戶輸入的字符串,將其拆分為單個字符,然后將其添加到帶有空格的“字符”列表中。
我嘗試過使用for循環來執行此操作,然后打印出結果,但是只要用戶輸入的字符串中有空格,它就會始終停止。
誰能幫我下一步做什么。 我也是一個新的Java程序員,所以請不要給出真正復雜的代碼來解決它。
import java.util.Scanner;
import java.util.ArrayList;
public class CaesarCipher {
protected final static String alphabet = "abcdefghij klmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890,.'(){}[]";
public static void main(String[] args) {
//Declares the scanner class that is used to read the user's input from the keyboard
Scanner input = new Scanner(System.in);
//Asking the user for a shift value for encryption
System.out.println("Please enter a shift value:");
int shiftVal = input.nextInt();
//Asks the user for a string that they want to be encrypted
System.out.println("Please enter the message that you want to be encrypted:");
String msg = input.next();
//A String that will store the encrypted message
String encryptedMsg = "";
ArrayList<Character> chars = new ArrayList<>();
}
}
您可以通過toCharArray()
將String拆分為chars,然后可以像這樣移動它們:
int shiftVal = 5;
String whatever = "dfsfsdf";
char[] whateverArr = whatever.toCharArray();
for (int i = 0; i < whateverArr.length; i++) {
whateverArr[i] += shiftVal;
}
String whateverEnc = String.valueOf(whateverArr);
另一種不使用toCharArray()
:
char[] whateverArr = new char[whatever.length()];
for (int i = 0; i < whateverArr.length; i++) {
whateverArr[i] = (char) (whatever.charAt(i) + shiftVal);
}
String whateverEnc = String.valueOf(whateverArr);
我還沒有測試過哪一個更快,但是我認為區別應該很小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.