This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
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);
}
GuitarString[] gStrings = new GuitarString[keyboard.length()];
will result in an array of GuitarString objects with the size of keyboard.length() all initialized with null value. You have to initialize each GuitarString object in the array before using it in the for loop in the line sample+=gStrings[i].sample();
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In this server app i am extending there is a class EventManager with a method:
pubic void addEvent(Event event, int time){ // code to process handling of events }
Event is and interface. I have several classes in which i need to run a very similar event that uses a lot of the same methods. Rather than rewriting each of those methods in each of the classes that i am running similar events in, i thought that if i created public class that implements event and had each of the methods in it:
public class someEvent impements Event{
public void send(String message){
for (int i = 0; i < Server.playerHandler.players.length; i++) {
if (Server.playerHandler.players[i] != null) {
if (Server.playerHandler.players[i].inPcGame()) {
Client c = (Client)Server.playerHandler.players[i];
c.sendMessage(message);
}
}
}
}
public void spawn(int[] npcs, wave){
int x = 4234;
int y = 2343;
int z = 1;
int health = 10 * wave;
int maxHit = 5 * wave ;
int attack = 150;
int defence = 200;
NpcHandler.getNpcHandler().spawnNpc(c, 1, x, y, z, 0, health, maxHit, attack, defence, true, false);
}
// Event method override
public void executeEvent(){
spawn(npcList, waveNum);
send(message);
}
}
Then use to then create objects in each of the class am running the events in. Then pass those objects to the EventManager.
I taught myself and am still learning, my friend who also taught himself, but has been programming longer says i should do that and should do this instead:
import sever.event.EventManager;
public class someClass {
public void send(String message){
for (int i = 0; i < Server.playerHandler.players.length; i++) {
if (Server.playerHandler.players[i] != null) {
if (Server.playerHandler.players[i].inPcGame()) {
Client c = (Client)Server.playerHandler.players[i];
c.sendMessage(message);
}
}
}
}
public void spawn(int[] npcs, wave){
int x = 4234;
int y = 2343;
int z = 1;
int health = 10 * wave;
int maxHit = 5 * wave ;
int attack = 150;
int defence = 200;
NpcHandler.getNpcHandler().spawnNpc(c, 1, x, y, z, 0, health, maxHit, attack, defence, true, false);
}
EventManager.getSingleton().addEvent( new Event(){
public void executeEvent(){
spawn();
send();
}}, 12000
);
}
and do this in each class rewriting each of the methods in each class i use the event in.
He insists that my way uses more memory and is CPU intensive. I do not understand how my way is heavier on the CPU instead of less intensive than his way. Which way is the correct way and why?
maybe you're sorta right and your friend's sorta wrong, though
maybe you're sorta wrong and your friend's sorta right, though
what you want is utility methods in a base class:
what your friend likely wants is for the event manager to have the closure in case of an exception:
Events are exactly the same event every time. They can be the only impetus for a programme; you want to see them up front.
class AWholeProgram {
static EventManager E = new EventManager();
public static void main(String[] args) {
E.add ( new PhoneCall("15555551212") );
E.add( PrintBatteryLevel );
E.add( PlaySong );
E.add( WaitForIncomingCall );
}
// so the "events", the only things that can happen, are up front...
final static Event PrintBatteryLevel = ...;
final static Event PlaySong = ...;
final static Event WaitForIncomingCall = ...;
final static Event PhoneCall = new phoneCall("15555551212")...;
class phoneCall extends Event {
long number = Long.parseString("15555551212");
phoneCall( String s ) {
//convert to digits, and look in the phone book, and see if its long distance, etc.
}
public void fireEvent() {
// makes the phone call
}
}
}
It makes a big difference where the phone number is. If it is tucked away in the event manager class, hehe...
Its really obvious what the program does, also, its really obvious what the program could do,
and better yet, its really obvious that the program doesn't do anything else.
Many programs kick off with the gui, frames packing and whatnot, and way over in some bit of handler there's a button, which, if clicked deletes a file, or worse. ouch..
You likely want all the events in one file. Yikes.
like this...
class BaseEvent {
// every event logs
public void fireEvent( Event e ) {
log.print( event );
}
String toString() {
return getClass.getName();
}
}
class PlayerEvent extends BaseEvent {
player p; // every player event has an associated player (and logs, and has a toString method..)
public void fireEventWithPlayer( Player x, Game g ) {
g.spawn( x );
super.fireEvent( this ); ///
}
}
class GameEvents implements BaseEvent {
startGame, endGame, createGame, ...
}
/// just where should the spawn event be?
/// then add the event manager,
/// a main method that goes through all the steps, so you can see how your logs will look...
/// and at the end pre-define all your events.
/// you'll have **lots** of events in categories (player, game, network, etc.)
Answer to question?
implementing an interface the way your friend suggests is almost identical to creating an anonymous inner class which is in scope at the point of declaration. a new instance is created for each call and the quantity of data passed with the "interface method" is dependent on the quantity of data that is in scope at the declaration.
with predefined events the data is low and the cpu is fast. More classes is better than more definitions.
The JVM can optimize the cats off a rug if you declare stuff far enough in advance. Your friend is right, if your were writing in C, or an untyped dynamic language, or even a JVM that couldn't optimize well. Syntactically, you need to keep in mind that the event will run in the event manager's run thread and not at the point where the object is defined.
Your method has two variables
addEvent(Event event, int time)
how will it work with a different signature?
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
This is my code. I just read file that have lines first is number then lines as string their number equal the number in first line.
import java.io.*;
import java.util.*;
class groupmember
{
int recieving;
int giving;
String name;
groupmember()
{
recieving=0;
giving=0;
//name=null;
}
public void setname (String Title)
{
this.name = new String(Title);
}
public void setrecieving(int val)
{
recieving=val;
}
public void setgiving(int val)
{
giving=val;
}
public String getname()
{
return name;
}
public int getrecieving()
{
return recieving;
}
public int getgiving()
{
return giving;
}
}
class gift1 {
/**
* #param args
*/
public static void main(String[] args) throws IOException{
BufferedReader f=new BufferedReader(new FileReader("gift1.in"));
PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter("gift1.out")));
StringTokenizer st=new StringTokenizer(f.readLine());
int NP=Integer.parseInt(st.nextToken());
int excpectedgived=0,div=0;
groupmember []groupmember=new groupmember[NP];
for(int i=0;i<NP;i++)
{
st=new StringTokenizer(f.readLine());
String name=st.nextToken();
groupmember[i].setname(name);
System.out.println(name);
}
out.close();
}
}
The problem arises on this line:
groupmember[i].setname(name);
It causes NullPointerException. I want to know why this happens.
An array of reference type variables is filled with null entries after initialization. You need
groupmember[i] = new groupmember();
before you can do:
groupmember[i].setname(name);
In future, please follow the Java Naming Conventions and have your classes start with an uppercase letter, like GroupMember (even CamelCase).
groupmember[i] is never defined, you need to add
groupmember[i] = new groupmember();
or something like that at the start of your cycle.
You have just initialised the array of type groupmember, now all the values in the array are null, in order to start using the array, you need to do .
groupmember[i] = new groupmember();
Do this: String name = ""; String have default value null if they are not initialized.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have this problem with my code. Its called java.lang.nullpointerexception. and I cant seem to fix it. please help me take a look at it. Thank you. I didnt include the class name and import. class name is called CHORD. I didnt make public static since my assginemnt say dont use global variable.
private ArrayList<Integer> nodeList;
public static void main(String[] args){
CHORD obj = new CHORD();
obj.nodeList = new ArrayList<Integer>();
String filename ="";
if(args.length ==1){
filename = args[0];
obj.read(filename);
}
}
public void read(String file){
CHORD obj = new CHORD();
obj = null;
Scanner loadFile = null;
try{
loadFile = new Scanner(new File(file));
String inputLine;
while(loadFile.hasNextLine()){
inputLine = loadFile.nextLine();
String[] inputArray = inputLine.split(" ",3);
if(inputArray[0].equalsIgnoreCase("init")){
int size = Integer.parseInt(inputArray[1]);
setSizeFT(init(size));
}
else if(inputArray[0].equalsIgnoreCase("addpeer")){
System.out.println("adding");
nodeList.add(Integer.parseInt(inputArray[1]));
}
}
}
catch(FileNotFoundException x){
}
finally{
System.out.println(getFT());
loadFile.close();
}
System.out.println(getFT());
}
public void print(){
CHORD obj = new CHORD();
for(int x =0; x< obj.nodeList.size(); x++){
System.out.println(obj.nodeList.get(x));
}
}
public int init(int num){
int n = 23;
double k = Math.ceil(Math.log(n)/Math.log(2));
int size = (int)k;
return size;
}
public void setSizeFT(int size){
sizeFT = size;
}
public int getFT(){
return sizeFT;
}
}
Here's an explanation of what NullPointerException's are: http://antwerkz.com/dealing-with-nullpointerexceptions/ From the article:
The most common (and obvious to the seasoned developer) is that you didn't initialize a variable.
Looking at that line, it looks like obj.nodeList may be null. Here's how I deduced that:
I can see that obj is not null, because the first line is CHORD obj = new CHORD();. That means you didn't set obj to null.
I can tell that Integer is not null. That's a class and you're calling a static method. That can't be null because there's nothing to be assigned there.
inputArray[1] may return null, but if that were happening, your stack trace would not end on this line, it would probably end on some line inside Integer.parseInt. I'd need to see a full stack trace to be sure though. But looking at the javadoc of Integer.parseInt, it doesn't say it'll throw a NPE so that's even more evidence to rule it out.
If inputArray was null, you'd probably get the error on the first if statement so I can rule that out.
Somewhere your code needs to do a obj.nodeList = new NodeList() or something like that. I can't say for sure without seeing what the CHORD class looks like.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
// my first class
public class FirstProject{
int first_number;
public FirstProject(){
first_number = 0;
}
public FirstProject(int Fn){
first_number = Fn;
}
public void Print(){
System.out.println("First number = " + first_number); System.out.println();
}
}
//second class in a separate file
// keep getting an error on this class saying that cannot find the . in p1.print();
public class TestProgram {
public static void main(String[] args){
FirstProject p1 = new FirstProject(10);
p1.print(); System.out.println();
}
Java is case-sensitive:
p1.Print();
But better change
public void Print(){ -> public void print(){
Since methods should not start with a capital letter, according to conventions.
That is simply because you created it as public void Print and are calling it as print. Java is case sensitive ;)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
In File1.java I have-
public static int[] dataArray = new int[100];
in File2.java I am accessing it as -
private static int[] data = new int[File1.dataArray.length];
for(int i=0; i<File1.dataArray.length; i++) {
if(File1.array1[i] == 0)
continue;
data[i] = File1.array1[i];}
Is this the right way or can I do like this-
private static int[] data = File1.dataArray;
to copy it? Any help appreciated. Thanks!
Yes, you can do
private static int[] data = File1.dataArray;
But there is a HUGE DANGER doing it that way and therefore I wouldn't call it the right way to COPY arrays, because you are not REALLY copying.
See this code. It demonstrates what happens.
public class File1
{
public static int[] dataArray = new int[100];
static
{
for (int i=0; i<100; i++)
{
dataArray[i] = i;
}
}
}
public class File2
{
private static int[] data = File1.dataArray; // makes "data" refer to the SAME array as File1.dataArray
public static void main(String[] args)
{
File2 file2 = new File2();
file2.data[20] = -567; // this changes File1.dataArray also!
System.out.println(File1.dataArray[20]); // prints -567
}
}
Therefore, use System.arrayCopy() to copy arrays, as Jarrod suggested. Of course, you can also copy by writing your own code like this -
private static int[] data = new int[File1.dataArray.length];
static
{
for(int i = 0; i < File1.dataArray.length; i++)
{
data[i] = File1.dataArray[i];
}
}
Look up System.arraycopy() to copy arrays.
It isn't clear what the presented code has to do with Files as referenced in your title?
Also your presented code is incomplete, won't compile and isn't clear or idiomatic Java.
This will most likely get closed if you don't make it clearer what you want to do.