1

So I made a folder called util and placed four classes along with program named unit10Assignment in it. I created a package util and typed " package util; " at the top of each one of the classes code like this:

package util;

public class Employee

Then i wrote:

import util.*;
import javax.swing.JOptionPane;

public class unit10Assignment

On top of the program. However when I compile it, it tells me. Anyone know why? I tried playing around with it and it disappeared when I typed in import java.util*; instead but I'm not sure that what my teacher wanted as her example did not have the java in front.

It also says " bad source file" "package does not contain class Employee " However, everything compiled and ran perfectly before I typed in the package statement and I have not made any change to the code since then. If I removed the package statement from the employee class tho, the same message would appear but it would say another class does not exist.

Thanks for any help Note: whether or not i put java.util or just util, this problem with the bad source still appears.

thanks for any help

David Robinson
  • 77,383
  • 16
  • 167
  • 187
Albert Dong
  • 99
  • 2
  • 3
  • 10

2 Answers2

3

I'm going to make the assumption that you have your project set up like this:

util/
    Employee.java
    unit10Assignment.java
bin/

(If it isn't, that's fine - so long as they're in some folder. bin/ should exist, though.)

The way that packages work is that they're folders on the hard drive - the package you want to import requires that the folder and class you wish to import both exist in that specific folder. This is why packages are handy - you can have two classes named Employee and have them live in completely different locations.*

Here's how you compile these into a package-like structure without the use of an IDE. Substitute $HOME for the full path of your Java class folder.

javac -sourcepath $HOME/util -d $HOME/bin *.java

And here's how you run your main class:

java -cp $HOME/bin util.$MAIN_CLASS

A breakdown of what these flags mean:

  • -sourcepath instructs javac to look in this specific directory for your source files.
  • -d specifies an output directory for your .class files.
  • -cp instructs java to add this folder to its classpath.

*: Really, really large projects can often use the same name as other classes; if you wanted to use a specific one, you'd have to use the fully-qualified class name for it.

Community
  • 1
  • 1
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • It's just a folder, much like `util/` is. Usually that's where binaries live in a project (hence **bin**). – Makoto Aug 25 '12 at 15:36
0

Make sure that:

  • the filename matches the class name (e.g. Employee.java for class Employee)
  • the files are inside the corresponding folder according to their package (i.e. util)

Are you using any IDE? If not, using one realy helps a lot with this kind of things.