In my project I have a server that handles multiple clients that connect to it. Each time a client is connected, a new “Guitar” is created, specific to that client on a new thread. Each “Guitar” is an array of 12 guitar strings, and when a key corresponding to a string is pressed in the client window, that guitar’s string is plucked.
I have a method called notePlayed(char key) in my Guitar class that “plucks” the string and adds all of the “plucks” into the combined audio to be played. However, I am running into this error anytime it is called:
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)
My guitarserver looks like this:
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);
}
with the new Guitar and threads created in the GuitarServer class further down
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();
and my Guitar class looks like this:
public class Guitar {
private static String keyboard;;
private static GuitarString[] gStrings;
public Guitar (GuitarString[] gStrings, String keyboard){
this.keyboard=keyboard;
this.gStrings=gStrings;
}
with the for-loop causing the error here:
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();
Sorry about the length of the post, but can anybody point me in the right direction or let me know how far off I am? Thanks in advance. I am happy to answer anymore questions you may have.
In the main function of Guitar I initialize the guitarstrings with this loop:
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);
}
will result in an array of GuitarString objects with the size of
keyboard.length()all initialized withnullvalue. You have to initialize each GuitarString object in the array before using it in the for loop in the linesample+=gStrings[i].sample();