-1

在我的项目中,我有一个服务器来处理连接到它的多个客户端。每次连接客户端时,都会在新线程上创建一个特定于该客户端的新“吉他”。每个“吉他”是一个由 12 根吉他弦组成的数组,当在客户端窗口中按下与一根弦相对应的键时,该吉他的弦就会被拨动。

我的 Guitar 类中有一个名为 notePlayed(char key) 的方法,它“弹奏”字符串并将所有“弹奏”添加到要播放的组合音频中。但是,只要调用它,我就会遇到此错误:

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)

我的吉他服务器如下所示:

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);
        }

在 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);
    }   
4

1 回答 1

1
 GuitarString[] gStrings = new GuitarString[keyboard.length()]; 

将产生一个 GuitarString 对象数组,其大小为keyboard.length()所有已初始化的null值。您必须先初始化数组中的每个 GuitarString 对象,然后才能在该行的 for 循环中使用它sample+=gStrings[i].sample();

于 2012-12-17T01:28:35.043 回答