mvb
mvb

Reputation: 701

Cannot find symbol even though class exists

This might be a very simple problem indeed, but I am absolutely new to Java, and not getting how to resolve it.

I have a stdlib.jar file which has some Classes defined like StdRandom and I have to to use them in my program. I read, that to use files like stdlib.jar I have to use the default package. So I removed the "package algs4" from my program below. But it didn't work.

package algs4;
public class PercolationStats
{
   //Some method declarations
   public static void main(String[] args)
   {
      //Some code
      for(int counter=0; counter<T; counter++)
      {
        while(!p.percolates())
        {
            iIndex = StdRandom.uniform(N);
            jIndex = StdRandom.uniform(N);
            ...
        }
      }



} 

Every time I compile this program using:

javac -cp . algs4/PercolationStats.java

I get the error:

algs4/PercolationStats.java:30: cannot find symbol
symbol  : variable StdRandom
location: class algs4.PercolationStats
                iIndex = StdRandom.uniform(N);

I also tried to compile using:

javac -cp .:stdlib.jar algs4/PercolationStats.java

But the error remains same.

Though it is not a good practice, I also extracted the files from the .jar file, which gave me the StdRandom.java file, but it still doesn't work.

All my files including the stdlib.jar are in the same directory.

How should I go about it?

EDIT: Just to make the question more elaborate for any future references: stdlib.jar used in the program was in a "default" package.

Upvotes: 2

Views: 14146

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503469

EDIT: If StdRandom isn't in a package, then you may indeed need to take your code out of a package too. (I'll give it a try - it's a long time since I've had to work with a class which wasn't in a package.)

In general, it would be much better to get a version of stdlib.jar which had the classes in packages.


We don't know what package StdRandom is in. You probably just want an import statement:

import foo.bar.StdRandom;

... where foo.bar is the package containing StdRandom. Alternatively, you can import all the classes in a package with a wildcard:

import foo.bar.*;

See the "Creating and using packages" part of the Java tutorial for more details.

You'll definitely need to have stdlib.jar in your classpath though, so stick to your second compilation approach.

You might also want to consider using an IDE (e.g. Eclipse) which can make all of this easier for you, and even work out import statements on demand.

Upvotes: 6

MaVRoSCy
MaVRoSCy

Reputation: 17849

try compiling with

java -classpath "lib/*:." my.package.Program

or

java -cp "Test.jar:lib/*" my.package.MainClass

see Setting multiple jars in java classpath for more info

Upvotes: 0

Related Questions