代码如下
分别是enum和testclass两个java文件
package cs121assignment1;
public enum Food {
APPLE("fruit", 55),
BANANA("fruit", 80),
CARROT("vegetable", 60);
private final String catagory; //vegetable or fruit
private final int calorie;
Food(String catagory, int calorie){
this.catagory = catagory;
this.calorie = calorie;
}
public int getCalorie(){
return calorie;
}
public String getCatagory(){
return catagory;
}
}
package cs121assignment1;
public class TestFood {
public static void main(String[] args){
System.out.println("All foods:");
for(Food food : Food.values()){
System.out.printf("%s, catagory: %s, calorie: %d kilocalorie each\n", food, food.getCatagory(), food.getCalorie());
}
}
eclipse中运行结果如下:
但是用命令行执行javac的时候显示如下:
cd Desktop;
javac cs121assignment1.TestFood;
不要
cd Desktop/cs121assignment1;
Delete all the package statements in the first line of the code
will run successfullycd to the folder containing the .java file
Execute
javac *.java
javac *.java
得到两个.class文件
java TestFood
Get two .class filesjava TestFood code>
This problem is actually a problem with the usage of package
Another method is not to remove the package in the first line of the file
javac -d ~/Desktop/cs121assignment1 Food.java TestFood.java
会生成一个以
cs121assignment1
为命名的新文件夹包含Food.class 和 TestFood.class
在新生成的
cs121assignment1
的上层目录用java cs121assignment1.TestFood
javac -d ~/Desktop/cs121assignment1 Food.java TestFood.java
cs121assignment1
containsFood.class and TestFood.class
🎜Usejava in the upper directory of the newly generated
will run successfully🎜cs121assignment1
cs121assignment1.TestFood