繁体   English   中英

Java中2D锯齿状阵列上的边界异常

[英]Out of Bounds Exception on a 2D Ragged Array in Java

问题解决了,我最终需要为阵列位置使用单独的计数器。 谢谢您的帮助! 我正在编写一个小型应用程序,该应用程序需要一个字符串,将每个字符串处理为7位二进制代码,然后根据该字符串填充音阶。 例如,如果我有二进制文件1000100,则在C Major的键中会给我音符C和G(C 0 0 0 G 0 0)。

我遇到了一段特定的代码问题,该代码采用String []输入(其中每个元素是一个单独的字符,值二进制7位),然后处理字符串中的每个字符并存储索引字符串中出现1的数目。 例如,字符串1000100将输出1和5。

这是执行此操作的方法:

public static String[][] convertToScale(String[] e){
    String[][] notes = new String[e.length][]; //create array to hold arrays of Strings that represent notes
    for(int i = 0; i < e.length; i++){
        notes[i] = new String[findOccurancesOf(e[i])]; //create arrays to hold array of strings
        for(int x = 0; x < e[i].length(); x++){ 
            if((e[i].charAt(x)) != 48){ //checks to see if the char being evaluated is 0(Ascii code 48)
                notes[i][x] = Integer.toString(x + 1); // if the value isn't 0, it fills in the array for that position.the value at x+1 represents the position of the scale the note is at
            }
        }
    }
    return notes;
}

这是用于获取e [1]中1出现的代码:

public static int findOccurancesOf(String s){
    int counter = 0;
    for(int i = 0; i < s.length(); i++ ) {
        if( s.charAt(i) == 1 ) {
            counter++;
        } 
    }
    return counter;
}

我遇到的问题是convertToScale方法。 当使用“ Hello world”作为我的输入时(在使用任何一种方法对输入进行处理之前,输入都已转换为7位二进制数),它会第一次通过第二个for-each循环,但是在尝试填充数组中的另一个点,它会抛出

java.lang.ArrayIndexOutOfBoundsException:3

编辑:它出现在行notes[i][x] = Integer.toString(x + 1); convertToScale方法。 在尝试了下面的提议更改之后,我已经多次运行调试器,但在同一行仍然遇到相同的错误。 findOccurancesOf方法返回正确的值(当评估H(1001000)时,它返回2。)所以令我感到困惑的是,超出范围异常在填充数组的第二个位置时就出现了。

另外,请随时告诉我是否还有其他疯狂的事情或我的语法不好。 谢谢!

findOccurancesOf()

if( s.charAt(i) == 1 ) {应该是if( s.charAt(i) == '1' ) {检查字符'1'。

否则,它将寻找ASCII值为1的字符。

存在一个超出范围的异常,因为如果findOccuranceOf()返回错误的值,那么在convertToScale()的以下行中, notes[i]长度不正确:

notes[i] = new String[findOccurancesOf(e[i])];

另外,您可能想要使用类似以下的内容:

notes[i][c++] = Integer.toString(x + 1);

如果我正确理解了您的意图,则将一些计数器c初始化为0。

AIOOBE的原因在于:

notes[i] = new String[findOccurancesOf(e[i])]; //create arrays to hold array of strings

在调用findOccurancesOf方法以查找字符串中出现1的位置时,请说您好,您找不到并返回0,然后调用notes[i][x] = Integer.toString(x + 1); x为0。由于您从未分配空间,因此数组绑定超出了异常范围。

我建议以下:

  • 在分配索引值大于0或其他值之前,请先验证您的字符串。
  • 将notes [i]初始化为notes[i] = new String[e[i].length];
  • 用单引号检查字符,例如a == '1'而不是a == 1

异常是由提到的almas引起的,但是请注意,您的逻辑错误最有可能在findOccurencesOf方法内,如果要在字符串中查找所有'1'字符,则必须更改为我在下面概述的内容,注意撇号。 否则,char将被转换为字节ASCII代码,并且除非与ASCII代码1匹配,否则该方法将返回0,从而导致异常

 if( s.charAt(i) == '1' ) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM