为什么在填充和组装2d数组矩阵时会出现错误



当我试图通过将构建方法放入打印方法中来获取字符串并将其放入数组时,但当我这样做时,我会得到以下错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at polycipher.CipherKey.printMatrix(CipherKey.java:27)
at polycipher.CipherKey.assembleMatrix(CipherKey.java:17)
at polycipher.ApplicationDriver.main(ApplicationDriver.java:23)

我想知道我在这里做错了什么?我很确定你可以在一个方法中调用一个方法,我的代码逻辑有问题吗?我试着在几乎所有我认为可能导致数组出界的地方加上-1,但没有运气。

import java.util.*;
import polycipher.Matrix;
public class CipherKey {
Scanner write = new Scanner (System.in);
Matrix polyCipher = new Matrix();
private final char[] PHRASE_KEY = { 'J', 'A', 'V', 'A'};
String[][] matrixStore = new String[PHRASE_KEY.length][PHRASE_KEY.length];
public void assembleMatrix()  { 
    matrixFormatter(polyCipher.translation);
    System.out.println(polyCipher.translation);
    printMatrix(buildeMatrix(polyCipher.translation,"|",","));
}

public String printMatrix(String s [][]){
    String keyOut = "  J A V An";
    for (int i = 0; i < PHRASE_KEY.length; i++) {
        keyOut += PHRASE_KEY[i] + " ";
        for (int j = 0; j < PHRASE_KEY.length; j++) {
            keyOut += s[i][j] + " ";
        }
        keyOut += "n";
    }
    return keyOut;
}
public static String [][] buildeMatrix (String translation, String outermarker, String innermarker) {
    // outerdelim may be a group of characters
    String [] sOuter = translation.split ("[" + outermarker + "]"); 
    int size = sOuter.length;
    // one dimension of the array has to be known on declaration:
    String [][] result = new String [size][]; 
    int count = 0;
    for (String line : sOuter)
    {
        result [count] = line.split (innermarker);
        ++count;
    }
    return result;
}
public String matrixFormatter(String x){
     String resultstr = "";
      int i = 0;
      while(i < x.length()) {
        // If end of string: only add character.
        if (i == x.length() - 1) {
          resultstr += x.substring(i, i + 1);
        } else {
          if ( ((i + 1) % 4) == 0) {
            resultstr += x.substring(i, i + 1)  + "|";
          } else {
            resultstr += x.substring(i, i + 1)  + ",";
          }
        }
        i++;
      }
      return resultstr;
}

}

这就是我在主中调用矩阵的方式

    CipherKey Key = new CipherKey();
    Key.assembleMatrix();

这是我翻译的课程:

import java.util.Scanner;
public class Matrix {
private final char[] CIPHER_KEY = { 'A', 'D', 'F', 'G', 'V', 'X' }; // static morse array
private final String validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // characters which can be used
public String translation = ""; // for storing it the translation of the phrase
{ // failsafe, our program will be stuck in an infinite loop if
    // number of valid characters is not at lease the square of CIPHER_KEY
    if(validChars.length() < CIPHER_KEY.length*CIPHER_KEY.length) {
        System.out.println("Error: Not enough valid characters to populate matrix.");
    }
}
private char[][] matrix = new char[CIPHER_KEY.length][CIPHER_KEY.length]; // field for holding the generated matrix
private int[] usedNumbers = new int[validChars.length()]; // field for enforcing unique characters
{ // initiate all array elements to -1 (our "empty" value)
    for (int x = 0; x < usedNumbers.length; x++)
        usedNumbers[x] = -1;
}
public Matrix() { // Matrix default constructor override
    int random; 
    for (int i = 0; i < CIPHER_KEY.length; i++) { // for every row
        for (int j = 0; j < CIPHER_KEY.length; j++) { // for every column
            validation: while (true) { // do this until I break the loop manually
                random = (int) (Math.random() * validChars.length()); // generates a random number from 0 (inclusive) to (36 exclusive)
                for (int k = 0; k < usedNumbers.length; k++) { // check every previously used character
                    if (random == usedNumbers[k]) {
                        continue validation; // if this char used before, skip it
                    } else if (usedNumbers[k] == -1) {
                        usedNumbers[k] = random; // if not previously used, store its value as used
                        break validation; // and break out of this validation loop
                    }
                }
            }
            matrix[i][j] = validChars.split("")[random].charAt(0); // add this character to the matrix
        }
    }
}
public void searchMatrix(){
    Scanner console = new Scanner (System.in);
    String phrase ="";
    System.out.println("n Enter the message you would like "
            + "to encrypt with the cipher: ");
    phrase = console.nextLine();
    char[] phraseSplit = phrase.toUpperCase().toCharArray();
    for (int k=0; k<phraseSplit.length; k++) {
        for (int i=0; i<matrix.length; i++) {
            for (int j=0; j<matrix[i].length; j++) {
                if (phraseSplit[k] == matrix[i][j]) {
                    System.out.printf("%c has a Array Index %d, %dn", phraseSplit[k], i, j);
                    if(i == 0){  translation += "A";  }
                    if(i == 1){  translation += "D";  }
                    if(i == 2){  translation += "F";  }
                    if(i == 3){  translation += "G";  }
                    if(i == 4){  translation += "V";  }
                    if(i == 5){  translation += "X";  }
                    if(j == 0){  translation += "A";  }
                    if(j == 1){  translation += "D";  }
                    if(j == 2){  translation += "F";  }
                    if(j == 3){  translation += "G";  }
                    if(j == 4){  translation += "V";  }
                    if(j == 5){  translation += "X";  }
                }//end if
            }//end for j
        }//end for i
    }//end for k
    System.out.println("");


 } //search end
public String toString() { // toString override, useful for debugging, prints out the matrix in a 6x6 table
    String output = "  A D F G V Xn";
    for (int i = 0; i < CIPHER_KEY.length; i++) {
        output += CIPHER_KEY[i] + " ";
        for (int j = 0; j < CIPHER_KEY.length; j++) {
            output += matrix[i][j] + " ";
        }
        output += "n";
    }
    return output;
}

}

您对Matrix.translation的默认值执行一些拆分操作,然后假设buildeMatrix操作创建了一个与matrixStore大小相同的2D数组。

这似乎是个坏主意。

按以下方式更改printMatrix方法:

public String printMatrix(String s [][]){
    String keyOut = "  J A V An";
    for (int i = 0; i < s.length; i++) {
        keyOut += PHRASE_KEY[i] + " ";
        for (int j = 0; j < s[i].length; j++) {
            keyOut += s[i][j] + " ";
        }
        keyOut += "n";
    }
    return keyOut;
}

并将您的assemblyMatrix方法更改为例如以下内容:

public void assembleMatrix()  { 
    polyCipher.translation = matrixFormatter(polyCipher.translation);
    System.out.println(polyCipher.translation);
    System.out.println(printMatrix(buildeMatrix(polyCipher.translation,"|",",")));
}

最新更新