我正在尝试编译我的 java 文件名Test.java。Test.java调用类com.api.APIUser.java,该类在user.jar文件中可用。我已将user.jar添加到 lib 文件夹中。但Test.java无法选择APIUser.java。当我使用编译Test.javajavac时出现错误
"package com.api does not exist".
Run Code Online (Sandbox Code Playgroud)
测试.java
import com.api.APIUser;
public class Test{
APIUser ap = new APIUser();
ap .login();
public static void main(String[] args){
//to do
}
}
Run Code Online (Sandbox Code Playgroud)
API用户
package com.api
public class APIUser{
public string login(){
//to do
return string;
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人知道我为什么会收到此错误。请建议我解决方案。提前致谢。
您的代码中有多个问题。
APIUser class;中的 com.api 导入没有行终止符下面是改进后的代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
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";
}
}
Run Code Online (Sandbox Code Playgroud)
还要确保 JAR 文件存在于类路径中。如果您不使用任何 IDE,则必须使用该-cp开关以及 JAR 文件路径,以便可以从那里加载类。
您可以使用下面的代码来了解如何使用命令提示符下的类路径来编译您的类。
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();
}
}
Run Code Online (Sandbox Code Playgroud)