Ok so I have a file called 'Sandwich.java' at the root folder and a file called 'SandwichType.java' inside of a folder at [root]/MyFrstPkg. For whatever reason it won't compile claiming that Sandwich.java cannot be found. Here is the directory structure:
root --
|
|- Sandwich.java
|
|-MyFirstPkg
|
|-SandwichType.java
Here is Sandwich.java:
//note I also tried adding package MyFrstPkg; in this file as well and removing the leading MyFrstPkg. from the import statement below, still no luck.
import MyFrstPkg.SandwichType; //the text 'MyFrstPkg' part is underlined as an error
class Sandwich{
SandwichType type; //the text 'SandwichType' is underlined as an error
public static void main(String[] args){
Sandwich sndwch1 = new Sandwich();
sndwch1.type = SandwichType.HAM; //the text 'SandwichType' is underlined as an error
System.out.println("A HAM costs $"+sndwch1.type.getCost());
System.out.println("and has "+ sndwch1.type.getSlices()+" slices.");
}
}
and here 开发者_StackOverflowis SandwichType.java:
package MyFrstPkg;
enum SandwichType{
HAM(0,0f);
SandwichType(int numSlices, float cost){ // constructor - Ryan changed 'numslices' to 'numSlices'
this.numSlices = numSlices;
this.cost = cost;
} //end constructor
private int numSlices; //These are specific to this
private float cost; // enum class...
public int getSlices(){
return numSlices;
}
public float getCost(){
return cost;
}
}//end of SandwichType enum
I browse in CMD to the root location and run 'java Sandwich.java' and all I get is a ClassNotFoundExeption Sandwich.Java, why is it not found? IT IS ITSELF D:
To compile your class, use
javac Sandwich.java
If this gives no error messages, you should be able to call
java Sandwich
to start your program.
If the first works without error, we are one step further. If the second does not work, try this instead:
java -cp . Sandwich
If it works this way, you have set some wrong classpath. Type echo %CLASSPATH%
and post the result. (Normally you should not need the CLASSPATH variable at all for simple projects.)
Netbeans is very project-based, so I'd try creating a basic Java Application
project and putting them in there.
The name of your project becomes the base package name if you choose "new project" then "java application". You would want to choose "java project with existing sources" if you already have the package/directory structure set up.
If you choose "java application" you can delete the default package name, then right click on the project name, choose "New" Then "Java Package ..." from the list.
EDIT: - Sorry... didn't notice. Your classes aren't public. That's your real problem.
public class Sandwich { ...
public enum SandwichType { ...
As for trying to run java Sandwich.java
... er, you can't. That's source code. It has to be compiled to a class first.
精彩评论