Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

java package does not exist and bad source file

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...