此程序是使用鍵盤琴鍵來彈奏音符。對於每個按鍵,我會得到一個不同的字符串索引,範圍從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;
}
}
}
}
}
是什麼鍵的值時調用?字符串'鍵盤'中有37個字符,字符佔據索引0-36。所以如果key> 36或<0,那麼你會得到一個'IndexOutOfBoundsException' –