这个程序是用键盘的按键来弹奏音符的。对于我按下的每个键,我得到一个不同的字符串索引,范围从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;
}
}
}
}
}发布于 2011-12-03 08:18:34
您希望调用String#indexOf(int),它将为您提供字符的索引。String#charAt(int)返回给定索引处的字符。
发布于 2011-12-03 08:23:11
您需要indexOf方法
返回此字符串中第一次出现指定字符的索引
而不是charAt
返回指定索引处的字符值。索引的范围从0到length() - 1。对于数组索引,序列的第一个字符值位于索引0,下一个字符值位于索引1,依此类推。
发布于 2011-12-03 08:26:34
问题出在这里:StdDraw.nextKeyTyped();文档显示:
用户键入的下一个密钥是什么?此方法返回与键入的键对应的Unicode字符(如'a‘或'A')。它不能识别操作键(如F1和箭头键)或修改键(如control)。
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;
}
}https://stackoverflow.com/questions/8364304
复制相似问题