在我的项目中,我有一个服务器,可以处理连接到它的多个客户端。每次连接客户端时,都会创建一个新的“吉他”,特定于新线程上的客户端。每个“吉他”是一个由12个吉他弦组成的数组,当在客户端窗口中按下与字符串对应的键时,将弹拨该吉他的弦。
我的Guitar类中有一个名为notePlayed(char key)的方法,它“拔出”字符串并将所有“plu”添加到要播放的组合音频中。但是,我在调用时遇到此错误:
key pressedj
Exception in thread "Thread-4" java.lang.NullPointerException
notePlayed accessed
at Guitar.notePlayed(Guitar.java:29)
at GuitarListener.run(GuitarServer.java:33)
at java.lang.Thread.run(Thread.java:680)
我的guitarserver看起来像这样:
class GuitarListener implements Runnable {
private Socket sock;
private GuitarListenerGui gui;
private Guitar guitar;
public GuitarListener(Socket s, GuitarListenerGui g, Guitar gt) {
this.sock = s;
this.gui = g;
this.guitar = gt;
}
public void run() {
boolean loop=true;
try {
//setting up printwriters and bufferedreaders removed
System.out.println("key pressed" + key);
Guitar.notePlayed(key);
}
使用新的Guitar和在GuitarServer类中进一步创建的线程
String keyboard ="qwertyuiop[]";
GuitarString[] gStrings = new GuitarString[keyboard.length()];
Guitar guitar = new Guitar(gStrings, keyboard);
GuitarListener job = new GuitarListener(serverSocket.accept(), gui, guitar);
// start a new thread to handle the connection
Thread t = new Thread(job);
t.start();
我的吉他课看起来像这样:
public class Guitar {
private static String keyboard;;
private static GuitarString[] gStrings;
public Guitar (GuitarString[] gStrings, String keyboard){
this.keyboard=keyboard;
this.gStrings=gStrings;
}
使用for循环导致错误:
public static void notePlayed (char key){
double sample=0.0;
for (int i=0; i<keyboard.length(); i++){//adds all of the strings to sample to be played
sample+=gStrings[i].sample();
对于帖子的长度感到抱歉,但有人能指出我正确的方向或让我知道我离我有多远吗?提前致谢。我很乐意回答您的问题。
在吉他的主要功能中,我用这个循环初始化吉他弦:
for(int i=0;i<keyboard.length();i++){
double iNote = 440.0* Math.pow(2, i/12.0);//puts the correct frequency with each string
System.out.println(iNote);
gStrings[i] = new GuitarString(iNote);
}
答案 0 :(得分:1)
GuitarString[] gStrings = new GuitarString[keyboard.length()];
将导致一个大小为keyboard.length()
的GuitarString对象数组全部初始化为null
值。您必须先初始化数组中的每个GuitarString对象,然后才能在行sample+=gStrings[i].sample();