问题解决了,我最终需要一个单独的计数器来表示数组位置。谢谢您的帮助! 我正在编写一个小应用程序,它接受一个字符串,将每个字符串处理为 7 位二进制代码,然后根据该字符串填充音阶。例如,如果我有二进制 1000100,在 C 大调中,它会给我音符 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
编辑:它出现在convertToScale方法的notes[i][x] = Integer.toString(x + 1);
行中。在尝试下面的建议更改后,我多次运行调试器,但在同一行仍然遇到相同的错误。 findOccurancesOf 方法返回正确的值(当计算 H(1001000) 时,它返回 2。)所以让我困惑的是,当它填充数组中的第二个位置时,就会出现越界异常。
此外,如果还有其他疯狂的地方或者我的语法很糟糕,请随时告诉我。谢谢!
最佳答案
在findOccurancesOf()
中:
if( s.charAt(i) == 1 ) {
应为 if( s.charAt(i) == '1' ) {
以检查字符“1”。
否则它将寻找 ASCII 值为 1 的字符。
存在越界异常,因为如果 findOccuranceOf()
返回错误值,则 notes[i]
不会在以下 convertToScale()
行中构造正确的长度:
notes[i] = new String[findOccurancesOf(e[i])];
此外,您可能想使用以下内容:
notes[i][c++] = Integer.toString(x + 1);
如果我正确理解你的意图的话,一些计数器c
初始化为0。
关于java - Java 中二维不规则数组的越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27087180/