如何编译和运行带有包的java类 [英] How to compile and run a java class with a package

查看:50
本文介绍了如何编译和运行带有包的java类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文件 MyClass.java 文件中有一个名为 MyClass 的类(代码如下)

package myclass;类我的类{公共 int add (int a, int b){返回 a+b;}公共静态无效主(字符串参数[]){MyClass obj = new MyClass();System.out.println(oobj.add(2, 3));}}

我正在用

编译类

javac MyClass.java

但我正在尝试使用

运行课程

java MyClass

java myclass.MyClass

我收到错误

错误:无法找到或加载主类 MyClass

但是,如果我省略了包名,我就可以运行这个程序.我哪里出错了?

解决方案

确保你在包文件夹(你编译的类文件所在的文件夹)的父目录中,并执行以下命令:

>

java myclass.MyClass

下面是一个示例文件结构:

bin->我的课->我的类.class

在上面的示例结构中,您必须从bin"目录执行命令.

另外,将类定义为public并重新编译java源文件.

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));
  }
}

I am compiling the class with

javac MyClass.java

But I am trying to run the class using

java MyClass

or

java myclass.MyClass

I am getting the Error

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

In the example structure above, you would have to execute the command from the "bin" directory.

Also, define the class as public and recompile the java source file.

这篇关于如何编译和运行带有包的java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆