【问题标题】:how to solve package does not exist error in java如何解决java中的包不存在错误
【发布时间】:2015-12-10 07:32:21
【问题描述】:

我正在尝试编译我的 java 文件名 Test.javaTest.java 调用 com.api.APIUser.java 类,该类在 user.jar 文件中可用。我在 lib 文件夹中添加了 user.jar。但是 Test.java 无法选择 APIUser.java。当我使用 javac 编译 Test.java 时出现错误

"package com.api does not exist".

Test.java

import com.api.APIUser;
 public class Test{
  APIUser ap = new APIUser();
  ap .login();
  public static void main(String[] args){
    //to do
  }

}

API用户

package com.api
public class APIUser{
  public string login(){
   //to do
   return string;
 }

}

如果有人知道我为什么会收到此错误。请建议我解决方案。 提前致谢。

【问题讨论】:

  • 您需要在 CLASSPATH 中传递 JAR。如果你使用的是 Eclipse IDE,你可以试试这个,stackoverflow.com/questions/179024/…
  • 感谢 subir 的回复,但我没有使用 eclipse,使用命令我正在做所有的工作。所以请告诉我们如何使用命令来完成它的解决方案。
  • 使用 javac -cp .;/lib/user.jar -D com.api.Test.java
  • @user3090158 你真的应该开始使用像 Eclipse 或 Netbeans 这样的 IDE。您的代码中有几个语法错误,使用 IDE 很容易检测到。

标签: java


【解决方案1】:

在 com.api 包后加分号,如下所示

package com.api;

清理并构建项目并运行如果有任何问题通知

【讨论】:

    【解决方案2】:

    您的代码中有多个问题。

    1. APIUser class 中的 com.api 导入没有行终止符;
    2. 您的登录方法存在语法错误。

    以下是改进后的代码:

    import com.api.APIUser;
    
    public class Test {
        // APIUser ap = new APIUser(); // This call should be in the method body,
        // there is no use to keep it at the class level
        // ap.login(); // This call should be in method body
        public static void main(String[] args) {
            // TO DO
            APIUser ap = new APIUser();
            ap.login();
        }
    }
    

    API用户

    package com.api; // added termination here
    
    public class APIUser {
        //access specifier should be public
        public string login(){
           //to do
           //return string;//return some value from here, since string is not present this will lead to error
             return "string";
         }
    }
    

    还要确保 JAR 文件存在于类路径中。如果您不使用任何 IDE,则必须使用 -cp 开关和 JAR 文件路径,以便可以从那里加载类。

    您可以使用下面的代码了解如何compile your class using classpath from command prompt

    javac -cp .;/lib/user.jar; -D com.api.Test.java
    

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多