【问题标题】:2d array out of bound exception in for-loopfor循环中的二维数组越界异常
【发布时间】:2017-12-15 15:30:06
【问题描述】:

我正在研究关键字柱状密码,但我不断收到数组越界异常,我尝试调试代码并尝试捕获以理解问题,但我做不到!

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 开始循环时得到的结果:

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

我应该得到什么:

根据自己了解的背景知识来判断自己 密码学

【问题讨论】:

  • 请编辑您的问题,使您的代码缩进清晰可见。
  • 您的代码无法编译。请发布可运行的代码。
  • 您发布的代码运行良好(进行了一些明显的调整以使其运行)。只需在方法末尾添加System.out.println(Arrays.deepToString(matrix));,您就会看到matrix 很好。您的问题可能出在您的 print 进程中。
  • @OldCurmudgeon 怎么样?我仍然在线程“main” java.lang.ArrayIndexOutOfBoundsException: 65 中遇到异常
  • @OldCurmudgeon 我又试了一次,它成功了,但我想在字符串中打印矩阵

标签: java arrays loops for-loop encryption


【解决方案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++;

            }

【讨论】:

    【解决方案2】:

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

    这里采用这种方法是您的代码的固定版本(检查代码中的 cmets 是否有更改的部分):

    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
    

    【讨论】:

      猜你喜欢
      • 2019-11-02
      • 1970-01-01
      • 2021-05-26
      • 2013-05-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多