This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes NetBeans IDE 7.2   Output Message interpretation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "NetBeans IDE 7.2   Output Message interpretation" Watch "NetBeans IDE 7.2   Output Message interpretation" New topic
Author

NetBeans IDE 7.2 Output Message interpretation

Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
I'm a new JAVA student going through the "Head First JAVA" book by Sierra and Bates. I made it through Chapter 12 with minor problems that I've always been able to figure out. I was facinated by the BeatBox example and jumped to the end of the book and then grabbed the Code Kitchen Appendix and did a cut and paste of the application to see what the final product would be like. After I compiled the program (without errors) and tried to run it, I get the following output:

Exception in thread "main" java.lang.ArraayIndexOutOfBoundsException: 0
at beatboxfinal.BeatBoxFinal.main(BeatBoxFinal.java:42)

Java Result: 1
BUILD SUCCESSFUL (total time: 13 seconds)



I am using NetBeans IDE 7.2 and simply did a cut and paste, yet nothing happens when I run the application other than that message. Any ideas for this true Greenhorn?
Thanks,
Rusty
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11150
    
  16

I would say that you are most likely trying to access beyond the end of your array, but without seeing the actual code, it is hard to get much more specific...


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Hi Fred, Thanks for responding. Attached is the code from the "Code Kitchen" provided with the book.
Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Fred,
It doesn't look like the file was attached in my last two notes. I'm trying again. This time as a .doc file. I've tried with a .java and a .txt but it strips these file types after I hit the submit button.
Thanks,
Rusty
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11150
    
  16

Generally, we'd ask you paste it into the thread itself. Please surround it with code tags, like this:
[ code][ /code]
only without the spaces.
Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Hi Fred,
I didn't want to do it this way because of the length of the program but I tried changing the file extension three times to get past the firewalls that are preventing the files from being sent. Anyway, here you go:

[code = java]
import java.awt.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import java.io.*;
import javax.sound.midi.*;
import java.util.*;
import java.awt.event.*;
import java.net.*;


public class BeatBoxFinal { // implements MetaEventListener

JPanel mainPanel;
JList incomingList;
JTextField userMessage;
ArrayList<JCheckBox> checkboxList;
int nextNum;
ObjectInputStream in;
ObjectOutputStream out;
Vector<String> listVector = new Vector<String>();
String userName ;
HashMap<String, boolean[]> otherSeqsMap = new HashMap<String, boolean[]>();
Sequencer sequencer;
Sequence sequence;
Sequence mySequence = null;
Track track;
JFrame theFrame;

String[] instrumentNames = {"Bass Drum", "Closed Hi-Hat",
"Open Hi-Hat","Acoustic Snare", "Crash Cymbal", "Hand Clap",
"High Tom", "Hi Bongo", "Maracas", "Whistle", "Low Conga",
"Cowbell", "Vibraslap", "Low-mid Tom", "High Agogo",
"Open Hi Conga"};
int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};


public static void main (String[] args) {
new BeatBoxFinal().startUp(args[0]);
}

public void startUp(String name) {
userName = name;
try {
Socket sock = new Socket("127.0.0.1", 4242);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
Thread remote = new Thread(new RemoteReader());
remote.start();
}
catch (Exception ex) {
System.out.println("couldn't connect - you'll have to play alone.");
}
setUpMidi();
buildGUI();
}

public void buildGUI() {
theFrame = new JFrame("Cyber BeatBox");
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout layout = new BorderLayout();
JPanel background = new JPanel(layout);
background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

checkboxList = new ArrayList<JCheckBox>();
Box buttonBox = new Box(BoxLayout.Y_AXIS);

JButton start = new JButton("Start");
start.addActionListener(new MyStartListener());
buttonBox.add(start);


JButton stop = new JButton("Stop");
stop.addActionListener(new MyStopListener());
buttonBox.add(stop);

JButton upTempo = new JButton("Tempo Up");
upTempo.addActionListener(new MyUpTempoListener());
buttonBox.add(upTempo);

JButton downTempo = new JButton("Tempo Down");
downTempo.addActionListener(new MyDownTempoListener());
buttonBox.add(downTempo);

JButton sendIt = new JButton("sendIt");
sendIt.addActionListener(new MySendListener());
buttonBox.add(sendIt);


JButton saveIt = new JButton("Serialize It"); // new button
saveIt.addActionListener(new MySendListener());
buttonBox.add(saveIt);

userMessage = new JTextField();
buttonBox.add(userMessage);

incomingList = new JList();
incomingList.addListSelectionListener(new MyListSelectionListener());
incomingList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane theList = new JScrollPane(incomingList);
buttonBox.add(theList);
incomingList.setListData(listVector);

Box nameBox = new Box(BoxLayout.Y_AXIS);
for (int i = 0; i < 16; i++) {
nameBox.add(new Label(instrumentNames[i]));
}

background.add(BorderLayout.EAST, buttonBox);
background.add(BorderLayout.WEST, nameBox);

theFrame.getContentPane().add(background);

GridLayout grid = new GridLayout(16,16);
grid.setVgap(1);
grid.setHgap(2);
mainPanel = new JPanel(grid);
background.add(BorderLayout.CENTER, mainPanel);


for (int i = 0; i < 256; i++) {
JCheckBox c = new JCheckBox();
c.setSelected(false);
checkboxList.add(c);
mainPanel.add(c);
} // end loop

theFrame.setBounds(50,50,300,300);
theFrame.pack();
theFrame.setVisible(true);
} // close method


public void setUpMidi() {
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
// sequencer.addMetaEventListener(this);
sequence = new Sequence(Sequence.PPQ,4);
track = sequence.createTrack();
sequencer.setTempoInBPM(120);

} catch(Exception e) {e.printStackTrace();}
} // close method

public void buildTrackAndStart()
{
// this will hold the instruments for each vertical column,
// in other words, each tick (may have multiple instruments)
ArrayList<Integer> trackList = null;

sequence.deleteTrack(track);
track = sequence.createTrack();


for (int i = 0; i < 16; i++){
trackList = new ArrayList<Integer>();
for (int j = 0; j < 16; j++){
JCheckBox jc = (JCheckBox) checkboxList.get(j + (16 * i));
if (jc.isSelected()){
int key = instruments[i];
trackList.add(key);
}
else
{
trackList.add(null);
}
} // close inner

makeTracks(trackList);
} // close outer

track.add(makeEvent(192,9,1,0,15)); // - so we always go to full 16 beats



try {

sequencer.setSequence(sequence);
sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY);
sequencer.start();
sequencer.setTempoInBPM(120);
} catch(Exception e) {e.printStackTrace();}

} // close method

//============================================================== inner class listeners

public class MyStartListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
buildTrackAndStart();
}
}

public class MyStopListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
sequencer.stop();
}
}

public class MyUpTempoListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
float tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((float)(tempoFactor * 1.03));
}
}

public class MyDownTempoListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
float tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((float)(tempoFactor * .97));
}
}

public class MySendListener implements ActionListener { // new - save
public void actionPerformed(ActionEvent a) {
// make an arraylist of just the STATE of the checkboxes
boolean[] checkboxState = new boolean[256];

for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (check.isSelected()) {
checkboxState[i] = true;
}
}

try {
out.writeObject(userName + nextNum++ + ": " + userMessage.getText());
out.writeObject(checkboxState);
} catch(Exception ex) {
ex.printStackTrace();
System.out.println("sorry dude. Could not send it to the server");
}

} // close method
} // close inner class

public class MyListSelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent le) {
if (!le.getValueIsAdjusting()) {
String selected = (String) incomingList.getSelectedValue();
if (selected != null) {
boolean[] selectedState = (boolean[]) otherSeqsMap.get(selected);
changeSequence(selectedState);
sequencer.stop();
buildTrackAndStart();
}
}
}
}

public class RemoteReader implements Runnable {
boolean[] checkboxState = null;
String nameToShow = null;
Object obj = null;

public void run() {
try {
while ((obj=in.readObject()) != null) {
System.out.println("got an object from server");
System.out.println(obj.getClass());
String nameToShow = (String) obj;
checkboxState = (boolean[]) in.readObject();
otherSeqsMap.put(nameToShow, checkboxState);
listVector.add(nameToShow);
incomingList.setListData(listVector);
}
}catch (Exception e) { e.printStackTrace(); }
}
}


//==============================================================

public void changeSequence(boolean[] checkboxState) {
for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (checkboxState[i]) {
check.setSelected(true);
}
else
{
check.setSelected(false);
}
}
}

public void makeTracks(ArrayList<Integer> list) {
Iterator it = list.iterator();
for (int i = 0; i < 16; i++) {
Integer num = (Integer) it.next();
if (num != null) {
int numKey = num.intValue();
track.add(makeEvent(144, 9, numKey, 100, i));
track.add(makeEvent(128, 9, numKey, 100, i+1));
}
}
}



public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);

}catch(Exception e) { }
return event;
}
}
[/code]


Thanks,
Rusty
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

And which of those lines of code is line 42, where the exception was thrown?
Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
new BeatBoxFinal().startUp(args[0]);
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11150
    
  16

so...you decided to ignore my request you use code tags?

I want to help you. I ENJOY helping people. So do hundreds of other users. But your job is to make it as easy as possible for us to help you. Using code tags is really one of the MINIMUM things expected around here - especially when someone (in this case, me) take the time to spell it out for you.

If what you are telling us is correct, when you make this call:



you are saying "pass the first element of the args array into the startUp method". However, the JVM is telling you that there AREN'T any elements in that array...I.e. the 0th element (the first one) doesn't exist.

args is populated by what you pass in when you start a program.

So, the question now becomes: How are you running this? I would guess you are typing "java BeatBoxFinal" - thus passing in no arguments. you need to do something like "java BeatBoxFinal fred"
Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Fred,
I'm sorry you got upset with me. I wasn't trying to ignore you, I simply didn't understand what you were asking for. I thought the easiest thing for me to do for you was to copy the code as it was provided to me from the Code Kitchen. I did a cut and paste from the file that is provided on wickedlysmart.com. With that said (along with my apology) I read what you provided. I am initiating a run by simply clicking on the Run button in NetBeans. However, I discovered in earlier applications from earlier chapters in the book, the method for passing an argument comes from changing the run properities (a customizable box). What I did was to experiment with an argument, I used "Fred"...for no other reason than to see what would happen. The result was this:

I got a message:
"couldn't connect - you'll have to play alone."

Then the BeatBox window poped up and had all thw frames/widgets that I was expecting to see. The music plays exactly as I expected to be able to program the music. So you have actually solved the problem. I'm sure I'll learn how to play with others soon.
Thanks,
Rusty
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11150
    
  16

The important thing here is:

Do you understand WHY this fixed the problem? I would rather spend an hour helping you UNDERSTAND the problem than 30 seconds giving you the complete solution. If all you got from my post was "I did this and problems solved", then I have failed.

One other note: in my (and many, many other people's) opinion, if you are a beginner, using Netbeans is a bad idea. You end up learning/fighting with Netbeans, and not learning java. You miss out on a lot of knowledge, since it does stuff for you behind the scenes.

Finally, I apologize if I sounded rude above. I had just gotten of a long, frustrating day at work. I should have waited before replying.

By all means, if you don't understand something - a tip given, a policy here, advice on how to post...please just ask someone. People here love to help.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11150
    
  16

One more note:

You might benefit from reading this FAQ.
Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Fred,
I really do appreciate the time and help you have and are providing. The way I have my work space (my home) set up is I have my work laptop set up so I can refer to things quickly on that computer as well as monitor email. I have my personal laptop next to it where I do my work and I control the computer as the admin. The reason I ended up trying NetBeans (and I think you observation is very accurate, at times I am fighting NetBeans) is that when I downloaded a jdk, I grabbed jdk1.6.0_33. It loaded in a file with the following path:

c:\Program Files\Java\jdk1.6.0_33\bin


After I downloaded the jdk I tried following the book that stated that I had to "add an entry to you rPATH environment variable that points to the /bin directory inside the main Java directory." I tried to follow the Javaranch guidance on how to do that but I couldn't get my computer terminial to know where the javac compiler was. In other words, when I used the command line entry "% javac", nothing would ever happen. I couldn't figure it out and I read the guide fairly close. I really wanted to learn the JAVA not fool with NetBeans. Eventually I want to understand this IDE as well as eclipse, but for now, I'm just trying to learn and understand JAVA. I'm a software system engineer by schooling and training. I understand the protocols and how systems work. But now I wanted to see what the actual code looked like, so I was trying to teach myself JAVA.

Anyway, you have been very helpful. I believe I understand why the code was not working, I needed an argument and I wasn't giving it. NetBeans doesn't allow you to type "run" with an argument added directly. There is a place to provide the argument when Run is selected and I hadn't used that feature properly before you made your suggestion. Once I read your response, it became clear why the application didn't do anything. I went back to the code and started reading it again to see what it expected. I think I'm beginning to understand. It is explained completely in later chapters of the book. But my jumping to the end caused me to skip a step in my learning. My bad.

Regards,
Rusty
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Rusty Neal wrote:... when I used the command line entry "% javac", nothing would ever happen.

You were not supposed to type the %. That's just the command line prompt. The command is named "javac", not "% javac".

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Fred,
So you can follow what I did and perhaps see what I'm doing wrong, here is how I tried to set up my PATH for the javac compiler.

Step 1.
From my Control Panel I selected System, Advanced tab, selected Environment Variables button. A window opened that showed the "User variables for Rusty". I had logged onto my laptop as Rusty. I followed the instructions from Javaranch to add a "New" variable called with the value, .

Step 2.
I then created a System variables "Path" with the value

However, when I go to my command line tool and type javac nothing happens.
Rusty
Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Okay Fred, I really am a newbie. When I changed the directory to the and then just typed at the commad line prompt, it gave a list of the java commands. So your guidance was spot-on and it seems to fix my problem. Does that also mean that I always have to go to the path to work with the javac compiler? If I were in the root directory nothing would work with java? Is that how the path works?
Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Fred,
With the little bit you have already provided, I've got the program running from the command line. It is much easier to launch the application that needs an argument from the command line. I learned that I have to save my applications code in the same directory as the javac compiler. When I did that and then compiled the code, it did create the classes that are expected. When I typed like I did with the NetBeans, it gave the same message that I would have to play alone and then launched the applications window.
So you have already helped me to understand the little subtle things I was missing. My next job is to pick up in the book where I had been and continue to follow using the command prompt instead of the NetBeans. Thank you very much,
Rusty
Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Jesper,
Thank you. I thought it was Fred that had added what you did. Between what you provided and what Fred provided, I'm up and running and not using the IDE. Thanks. This forum did help tremendously.
Regards,
Rusty
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11150
    
  16

Rusty Neal wrote:I learned that I have to save my applications code in the same directory as the javac compiler.

Honestly...that is a bad idea. And also not really true. You really want to keep your code separate from the JRE/JDK stuff. Really, you should keep code for each project in it's own directory, so it doesn't get intermingled...In any case...

I have a directory:

c:\slop

This is where I have written TONS of quick little programs to test/experiment with little bits of code. this is not where my compiler is. And in fact, I can compile code in here even if my cmd shell shows me sitting in a different directory.

javac.exe is a program. When you type "javac" on the command line, the OS looks first (I think) in whatever directory you are in. If it finds something called "javac.exe", it runs that program. If that program isn't found, the OS goes to the PATH variable. This is nothing but a list of directories. The OS goes through each of those directories, in order, and says "is javac.exe in this one? How about this one? This one???". Eventually, it will either find the exe, run it, and stop looking...or eventually it will run out of places to look and tell you "couldn't find that - sorry!!!".

So you want to put the directory to your javac.exe in you PATH. My path looks like this:
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Common Files\Lenovo;C:\Program Files\Lenovo\Client Security Solution;C:\Program Files\Common Files\Ulead Systems\MPEG;C:\strawberry\c\bin;C:\strawberry\perl\site\bin;C:\strawberry\perl\bin;C:\Program Files\Java\jdk1.6.0_23\bin;
C:/Python27;c:\sqlite;c:\unixtools;C:\Program Files\Novell\GroupWise

So you can see that "C:\Program Files\Java\jdk1.6.0_23\bin" is in there. so now, no matter what directory I am in when I type "javac xxxxx", my OS knows to (eventually) look in C:\Program Files\Java\jdk1.6.0_23\bin, it finds javac.exe, and can run it.

If you have a command shell/cmd window open and edit the path, that shell won't pick up the change. Only cmd windows opened AFTER the change it made will pick up the changes.

Once you have the correct directory in your path, you can then compile any file, any place. i have a file in c:\slop called "temp.java". I can do this:

c:\javac slop\temp.java

I am sitting in the root C:\ directory. I can type javac here, and the OS will look for and find the executable. Then I give it the path to the file. the file gets compiled.


Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Fred,
I hope you won't mind helping me again. I had things working out nicely but I'm getting a message that I don't understand. First let me provide the code and then I'll follow it up with the error message.



Then I get this message:


The book has had some really simple examples that when I typed them in, they worked. This set of code comes from the book where I did a cut and paste to save time typing. I thought I understood the concept the chapter was teaching, but I can't get the code to compile now.
Thanks,
Rusty

Rusty Neal
Greenhorn

Joined: Apr 20, 2011
Posts: 18
Fred,
Never mind, I found this as a common error. I forgot to add the .java extension to the file I saved. I'm sorry to have bothered you.
Rusty
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: NetBeans IDE 7.2 Output Message interpretation
 
Similar Threads
Confusing in wait notify
No Display
= operator
Brand Newbie having Scanner Problem
How to find out the list of all methods in a java class through NetBeans