【发布时间】:2011-12-03 00:14:43
【问题描述】:
这个程序是使用键盘按键来弹奏音符。对于我按下的每个键,我都会得到一个超出范围的不同字符串索引,范围从 1 的 49 到 m 的 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;
}
}
}
}
}
【问题讨论】:
-
key 被调用时的值是多少? String
keyboard共有 37 个字符,字符占用索引 0-36。因此,如果密钥 > 大于 36 或 IndexOutOfBoundsException