2011-12-03 66 views
0

此程序是使用鍵盤琴鍵來彈奏音符。對於每個按鍵,我會得到一個不同的字符串索引,範圍從49到1到109。但我總是得到這個錯誤信息。我是Java新手,任何幫助將不勝感激,因爲我已經檢查了一堆論壇,並沒有找到相當這種問題的答案。字符串越界,

的異常被拋出這一行:

nextnote = keyboard.charAt(key); 

這是我的代碼:

public class GuitarHero { 
    public static void main(String[] args) { 
     //make array for strings 
     double[] notes = new double[37]; 
     GuitarString[] strings = new GuitarString[37]; 
     int nextnote; 
     int firstnote=0; 
     double NOTE = 440.0; 
     String keyboard ="1234567890qwertyuiopasdfghjklzxcvbnm"; 
     //for loop to set notes 
     for(int i=0;i<37;i++){ 
      double concert = 440.0* Math.pow(2, (i-24)/12.0); 
      notes[i] = concert; 
      for(int j=0;j<37;j++){ 
       strings[j] = new GuitarString(concert); 
      } 
     } 
     while (true) { 
      // check if the user has typed a key; if so, process it 
      if (StdDraw.hasNextKeyTyped()) { 
       char key = StdDraw.nextKeyTyped(); 
       //charAt gets index of character in string 
       nextnote = keyboard.charAt(key); 
       //make sure value is within string 
       if(nextnote>=0 && nextnote<37){ 
        // pluck string and compute the superposition of samples 
       strings[nextnote].pluck(); 
        double sample = strings[firstnote].sample() 
          +strings[nextnote].sample(); 
        StdAudio.play(sample); 
        // advance the simulation of each guitar string by one step 
        strings[nextnote].tic(); 
        firstnote=nextnote; 
       } 
     } 
     } 
    } 
} 
+0

是什麼鍵的值時調用?字符串'鍵盤'中有37個字符,字符佔據索引0-36。所以如果key> 36或<0,那麼你會得到一個'IndexOutOfBoundsException' –

回答

1

您需要indexOf方法

返回此字符串指定的字符

,而不是charAt

中第一次出現處的索引返回的char值指定的索引。索引範圍從0到length() - 1。與數組索引相同,序列的第一個char值位於索引0,索引1的下一個索引值等等。

1

的問題是在這裏: StdDraw.nextKeyTyped();文件說:

什麼是一個由用戶輸入的下一個關鍵?此方法返回與鍵入的鍵相對應的一個 Unicode字符(如'a'或'A')。 它不能識別操作鍵(如F1和箭頭鍵)或修改鍵 (如控制)。

key是一個字符而不是此行的索引。請改爲:

int charIndexInKeyboard = keyboard.indexOf(key); 
if(charIndexInKeyboard == -1) // char not recognized 
nextnote = keyboard.charAt(charIndexInKeyboard); 

nextnote現在應該包含您想要的字符。

編輯:這是你的while循環看起來應該像現在

while (true) { 
    // check if the user has typed a key; if so, process it 
    if (StdDraw.hasNextKeyTyped()) { 
     char key = StdDraw.nextKeyTyped(); 
     int charIndexInKeyboard = keyboard.indexOf(key); 
     if(charIndexInKeyboard == -1){ 
      // Not recognized, just continue to next 
      continue; 
     } 
     nextnote = keyboard.charAt(charIndexInKeyboard); 
     // pluck string and compute the superposition of samples 
     strings[nextnote].pluck(); 
     double sample = strings[firstnote].sample() 
     +strings[nextnote].sample(); 
     StdAudio.play(sample); 
     // advance the simulation of each guitar string by one step 
     strings[nextnote].tic(); 
     firstnote=nextnote; 
    } 
} 
+0

感謝您的幫助! – bitva

+0

@bitva很高興工作。爲了將來的參考和幫助你的同胞發現正確的答案,請接受這個帖子作爲答案,如果它爲你工作:) – GETah