简体   繁体   English

如何在Java中正确实现包

[英]How to Properly Implement Packages in Java

I am learning how to use packages in Java, but I am running into trouble when trying to implement them. 我正在学习如何在Java中使用包,但是在尝试实现它们时遇到了麻烦。 I have a simple class called Main which appears as follows: 我有一个称为Main的简单类,它显示如下:

public class Main
{
    public static void main(String[]args)
    {
        System.out.println("Package Test...");
    }
}

The directory of this class is: C:\\Users\\MyComputer\\Desktop\\Packages\\Main.java 此类的目录是:C:\\ Users \\ MyComputer \\ Desktop \\ Packages \\ Main.java

When I compile this class, I run into no trouble. 当我编译此类时,我没有遇到任何麻烦。 However, when I add "package com.example.mypackage;" 但是,当我添加“ package com.example.mypackage;”时 to the top of the .java file, compile the program, and try to run the program, I receive the following error: "Error: Could not find or load main class Main" 到.java文件的顶部,编译程序,然后尝试运行该程序,我收到以下错误:“错误:找不到或加载主类Main”

What can I do to solve this problem? 我该怎么做才能解决这个问题?

If the path of your class is C:\\Users\\MyComputer\\Desktop\\Packages\\Main.java then your class is not in a package. 如果您的类的路径是C:\\Users\\MyComputer\\Desktop\\Packages\\Main.java则您的类不在包中。 In this instance "Packages" is your project folder, and it only contains the one java class. 在这种情况下,“ Packages”是您的项目文件夹,并且仅包含一个java类。

If you want package com.example.mypackage; 如果要package com.example.mypackage; to work, then your path needs to be: 要工作,那么您的路径需要为:

C:\\Users\\MyComputer\\Desktop\\Packages\\com\\example\\mypackage\\Main.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM