簡體   English   中英

for循環中的二維數組超出范圍的異常

[英]2d array out of bound exception in for-loop

我正在使用關鍵字列密碼,並且不斷使數組超出綁定異常,我嘗試調試代碼並嘗試捕獲以了解問題,但我做不到!

public Decryption (String cipherText, String keyWord) {

      cipherText = cipherText.replaceAll("\\s+","");
      cipherText = cipherText.toUpperCase();
      cipherText = cipherText.trim();

      keyWord = keyWord.toUpperCase();

      int column = keyWord.length();

      int row = (cipherText.length() / keyWord.length());
        if (cipherText.length() % keyWord.length() != 0)
          row += 1;

      char [][] matrix = new char [row][column];

      int re = cipherText.length() % keyWord.length();
       for (int i = 0; i < keyWord.length() - re; i++)
         matrix[row - 1][keyWord.length() - 1 - i] = '*';

      char[] sorted_key = keyWord.toCharArray();
      Arrays.sort(sorted_key); 

      int p = 0, count = 0; 
      char[] cipher_array = cipherText.toCharArray();

      Map<Character,Integer> indices = new HashMap<>();

      for(int i = 0; i < column; i++){

       int last = indices.computeIfAbsent(sorted_key[i], c->-1);
        p = keyWord.indexOf(sorted_key[i], last+1);
          indices.put(sorted_key[i], p);

           for(int j = 0; j < row; j++){
            if (matrix[j][p] != '*') 
            matrix[j][p] = cipher_array[count];
                    count++; 
                }}
}

我在以下地方遇到異常:

matrix[j][p] = cipher_array[count];

循環存在問題,如果我以j = 1開頭,它不會給我異常,但不會得到正確的結果(它不會顯示最后一行)

我要解密的密文:

YARUEDCAUOADGRYHOBBNDERPUSTKNTTTGLORWUNGEFUOLNDRDEYGOOAOJRUCKESPY

關鍵詞:

你自己

我從1開始循環時得到的結果:

判斷自己關於了解密碼的背景知識

我應該得到的是:

判斷自己的背景知識,以了解密碼學

我不確定,因為您的代碼不允許我對此進行驗證(沒有簡單的方法就無需深入研究即可檢查算法的輸出),所以...我認為解決方案是:

for (int j = 0; j < row; j++) {
            if (matrix[j][p] != '*'){
                matrix[j][p] = cipher_array[count];
                count++;
            }
        }

代替:

for (int j = 0; j < row; j++) {
                if (matrix[j][p] != '*')
                    matrix[j][p] = cipher_array[count];
                    count++;

            }

我認為,在這種情況下,將'*'附加到字符串的策略不是解決之道-就像您所做的那樣。 在構建網格時最好追加一些字符。

按照這種方法,這里是代碼的固定版本(請檢查代碼中的注釋以了解已更改的部分):

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Decryption {

    private final String result;

    public Decryption(String cipherText, String keyWord) {

        cipherText = cipherText.replaceAll("\\s+", "");
        cipherText = cipherText.toUpperCase();
        cipherText = cipherText.trim();

        keyWord = keyWord.toUpperCase();

        int column = keyWord.length();

        int row = (cipherText.length() / keyWord.length());
        if (cipherText.length() % keyWord.length() != 0)
            row += 1;

        int[][] matrix = new int[row][column];

        // Changed to calculate the irregular columns
        int re = column - (row * column - cipherText.length());

        char[] sorted_key = keyWord.toCharArray();
        Arrays.sort(sorted_key);

        int p, count = 0;
        char[] cipher_array = cipherText.toCharArray();

        Map<Character, Integer> indices = new HashMap<>();

        for (int i = 0; i < column; i++) {

            int last = indices.computeIfAbsent(sorted_key[i], c -> -1);
            p = keyWord.indexOf(sorted_key[i], last + 1);
            indices.put(sorted_key[i], p);

            // Changed: Detects the need of an extra character and fills it in case of need
            boolean needsExtraChar = p > re - 1;
            for (int j = 0; j < row - (needsExtraChar ? 1 : 0); j++) {
                matrix[j][p] = cipher_array[count];
                count++;
            }
            if(needsExtraChar) {
                matrix[row - 1][p] = '-';
            }
        }

        result = buildString(matrix);
    }

    public static void main(String[] args) {
        System.out.println(new Decryption("EVLNE ACDTK ESEAQ ROFOJ DEECU WIREE", "ZEBRAS").result);
        System.out.println(new Decryption("EVLNA CDTES EAROF ODEEC WIREE", "ZEBRAS").result);
        System.out.println(new Decryption("YARUEDCAUOADGRYHOBBNDERPUSTKNTTTGLORWUNGEFUOLNDRDEYGOOAOJRUCKESPY", "YOURSELF").result);
    }

    private String buildString(int[][] grid) {
        return Arrays.stream(grid).collect(StringBuilder::new, (stringBuilder, ints) -> Arrays.stream(ints).forEach(t -> {
            stringBuilder.append((char) t);
        }), (stringBuilder, ints) -> {
        }).toString().replace("-", "");
    }
}

如果運行此命令,則將打印:

WEAREDISCOVEREDFLEEATONCEQKJEU
WEAREDISCOVEREDFLEEATONCE
JUDGEYOURSELFABOUTYOURBACKGROUNDKNOWLEDGETOUNDERSTANDCRYPTOGRAPHY

暫無
暫無

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

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