簡體   English   中英

Java - 編碼字符串/將隨機(未使用)字母分配給特定字母

[英]Java - Encoding a string / Assigning a random (unused) letter to specific letters

我正在嘗試制作一個密碼程序,其中一串文本中的字母被其他隨機生成的字母替換。 例如,短語“Beggars can't be choosers”看起來像“rannlxm zlpo ra zbddmaxm”。

我當前的問題是,為特定字母生成的隨機字母未應用於字符串中的其他匹配字母(原始字符串中的所有“g”字符都應為“n”(或生成的隨機字母) 在編碼字符串中)。 我確信我缺少一個相對簡單的解決方案,因此非常感謝任何建議。

將我的 char 數組傳遞給我的編碼器方法后,我試圖遍歷數組中的元素以檢查匹配的字母值。 如果找到匹配的字母,編碼后的字符數組的相應索引應分配給先前為原始字母生成的隨機字母,直到原始文本字符串及其所有字母都被編碼。

//Method to create an encoded phrase
public static String phraseEncoder(char[] phrase) {
    Random rand = new Random();
    char letter = '*';              
    char randomLetter = '*';
    char[] encodedChars = new char[phrase.length];  //Char array that will hold the encoded letters
    String encodedPhrase = "";
    ArrayList<Character> encryptedChars = new ArrayList<Character>();

    //Iterate through the elements in the array list to encode the characters
    for (int i = 0; i < phrase.length; ++i) {
        randomLetter = (char)(rand.nextInt(26) + 'a');

        //Determine if the character at the current index is a letter
        if (Character.isLetter(phrase[i])) {
            letter = phrase[i];
            encodedChars[i] = randomLetter;

            //Check the rest of the array for matching characters
            for (int j = i + 1; j < phrase.length; ++i) {

                //If a matching letter is found, change it to the previously defined random letter
                if (phrase[j] == letter) {
                    encodedChars[j] = randomLetter;
                }

                //If a matching letter is not found, continue to check the rest of the loop
                else {
                    break;
                }
            }
        }

        //Character at current index is not a letter, add it to the encodedChars array and move to the next element
        else {
            encodedChars[i] = phrase[i];
        }
        encryptedChars.add(randomLetter);
    }
    encodedPhrase = String.valueOf(encodedChars);
    return encodedPhrase;
}

我已經嘗試創建一個ArrayList來保存我隨機生成的字母,這樣就不會重復隨機字母。 我的大腦正在讓我失望,我似乎無法弄清楚我現在做錯了什么。

您的代碼有兩個小問題:

  1. 在您的內部循環中,您正在增加外部索引。 它應該是j而不是i
 for (int j = i + 1; j < phrase.length; ++j) {
   // ...
 }
  1. 你過早地打破了你的內循環。 要么刪除else { break; } else { break; }或替換break; 隨着continue;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM