如何使用包编译和运行Java类 [英] How to compile and run a java class with a package
问题描述
我在MyClass.java文件中有一个名为MyClass的类(下面提到的代码)
I have a class called MyClass in the file MyClass.java file (code mentioned below)
package myclass;
class MyClass {
public int add (int a, int b){
return a+b;
}
public static void main(String args[]) {
MyClass obj = new MyClass();
System.out.println(oobj.add(2, 3));
}
}
我正在使用
javac MyClass.java
但是我正在尝试使用
java MyClass
或
java myclass.MyClass
我收到错误消息
Error: Could not find or load main class MyClass
但是,如果我省略了软件包名称,则可以运行该程序. 我要去哪里错了?
But, I am able to run this program if I omit out the package name. where am I going wrong?
推荐答案
确保您位于包文件夹(已编译的类文件所在的文件夹)的父目录中,并执行以下命令:>
Make sure that you are inside the parent directory of the package folder (the folder in which your compiled class file is), and execute the following command:
java myclass.MyClass
下面是一个示例文件结构:
Below is an example file structure:
bin
-> myclass
-> MyClass.class
在上面的示例结构中,您将必须从"bin"目录中执行命令.
In the example structure above, you would have to execute the command from the "bin" directory.
此外,将类定义为public
并重新编译Java源文件.
Also, define the class as public
and recompile the java source file.
这篇关于如何使用包编译和运行Java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!