4

So I want to mess around with a library I just downloaded called stdlib.jar (downloaded from http://introcs.cs.princeton.edu/java/stdlib/)

So I added the library to the project, and when I inspect the project it looks like this in netbeans: package inspector in netbeans

So it seems that the library is set up properly.

But then in my project when I try to use one of the library classes, it looks like this.

My Custom Audio Player Class

Mousing over the import statement at the top, says expected "."
And If I change the import statement to say import stlib.StdAudio it says that the library does not exist.
Any body know what the problem is?

wfbarksdale
  • 7,498
  • 15
  • 65
  • 88

3 Answers3

1

1) Get rid of the import statement.

2) Get rid of the package statement.

3) Put musicplayer.java directly in the folder /src

4)Right click on libraries in the project menu and add stdlib.jar

Rexcirus
  • 2,459
  • 3
  • 22
  • 42
1

All the source code of this library (which is pretty unusual: first time I encountered this) is in the default package, which means you don't have to import anything if your class is also in the default package. Just use the class name.

StdAudio.play(tone);

Just make sure it is in the classpath, but I think it is if I look at your screenshot from NetBeans.


Update: It seems like I'm wrong. At the bottom of the page, you can find this:

Q. If I use a named package to structure my code, the compiler can no longer access the libraries in stdlib.jar. Why not?
A. The libraries in stdlib.jar are in the "default" package. In Java, you can't access classes in the default package from a named package. If you need to use our standard libraries with a named package, you must put our libraries in a package, as in this solution.

So, you have to copy the classes into your project its package musicplayer.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
0

If you are using the Sedgewick textbook or Algorithms course on Coursera, this may be of help.

As it was mentioned above, the libraries in stdlib.jar are in the DEFAULT PACKAGE. In Java, you can't access classes in the default package from a named package. So you have to move your source files to a DEFAULT PACKAGE of your project. It means that you have to move your source musicplayer.java file from the ./src/MUSICPLAYER/ folder directly to the ./src folder of your project, then delete the MUSICPLAYER folder. Also you have to delete the "package MUSICPLAYER;" statement at the beginning of your source file(s).

Basically that's all you need to do. Now when you moved your source file(s) to the default package, and added "stdlib.jar" to Libraries, you would have no problem addressing the classes from the library. You don't need no "import" statment for them.