for循环中的2d数组超出绑定异常

时间:2017-12-15 15:30:06

标签: java arrays loops for-loop encryption

我正在研究关键字柱状密码并且我一直在使数组超出绑定异常,我已经尝试调试代码并尝试捕获以了解问题但我不能!

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

关键字:

  

YOURSELF

当我用1开始循环时得到的结果:

  

自己判断你的背景知识,了解CRYP

我应该得到什么:

  

自己判断你的背景知识   CRYPTOGRAPHY

2 个答案:

答案 0 :(得分:0)

我不确定,因为你的代码不允许我验证这一点(没有简单的方法来检查算法的输出而不进行挖掘),所以...我认为解决方案是:

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++;

            }

答案 1 :(得分:0)

我认为在这种情况下将'*'附加到字符串的策略不是可行的 - 就像你所做的那样。在构建网格时最好附加一些字符。

按照这种方法,这里是您的代码的固定版本(检查代码中的注释以了解更改的部分):

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