[英]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。由於您從未分配空間,因此數組綁定超出了異常范圍。
我建議以下:
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.