java - 为什么在填充和组装二维数组矩阵时会出现错误?

标签 java arrays string matrix multidimensional-array

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

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 A\n";
    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;

}

}

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

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

这是我从中获取翻译的类(class):

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, %d\n", 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 X\n";
    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 大小相同的二维数组。

这似乎是个坏主意。

按以下方式更改 printMatrix 方法:

public String printMatrix(String s [][]){
    String keyOut = "  J A V A\n";
    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;
}

并将您的 assembleMatrix 方法更改为以下内容:

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

关于java - 为什么在填充和组装二维数组矩阵时会出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29436739/

相关文章:

java - Riak Link 商店与 java

java - Alt+Tab 使用 Java 机器人

javascript - 基于字符串数组过滤对象数组 "with partial match"

c++ - 交换某些字符后生成的给定子字符串的最大数量的字符串?

c++ - 从输入文件中逐行输入并使用 strtok() 进行标记化,然后输出到输出文件中

java - 使用 Log4J 1.*,如何将两个包写入两个单独的文件?

gwt - 使用 Java 在 CouchDB 2.0 fauxton 中创建文档

python - Pyspark Dataframe - 如何根据列数组作为输入连接列

php迭代一个关联数组

Java:棘手的前缀字符串排序(ArrayLists)