[英]Why I am getting package not found error?
I have created two java files A.java
and B.java
.我创建了两个 java 文件
A.java
和B.java
。 Both classes are in same folder testjava
.这两个类都在同一个文件夹
testjava
中。
Code in A.java A.java 中的代码
package pkg;
public class A{
int data;
public void printer(){
System.out.println("I'm in A");
}
}
Code in B.java B.java 中的代码
package mypkg;
import pkg.*;
public class B{
void printer(){
System.out.println("I'm in B");
}
public static void main(String[] args){
A obj = new A();
obj.printer();
}
}
To compile first file I used: javac -d . A.java
要编译我使用的第一个文件:
javac -d . A.java
javac -d . A.java
which compiled with no errors and created A.class
in ./pkg
folder javac -d . A.java
编译没有错误并在./pkg
文件夹中创建A.class
To compile second file I am using javac -cp "./pkg" B.java
which gives me the following errors:要编译第二个文件,我正在使用
javac -cp "./pkg" B.java
这给了我以下错误:
My directory structure after compilation of A.java
:我的
A.java
编译后的目录结构:
What should include as my classpath
?我的
classpath
应该包括什么? I have read and tried other StackOverflow questions on the same topic but couldn't solve my problem.我已阅读并尝试过有关同一主题的其他 StackOverflow 问题,但无法解决我的问题。
无法从类型 A 对非静态方法printer() 进行静态引用。您正在从静态区域调用实例方法“printer()”。
Assuming your project directory looks like this:假设您的项目目录如下所示:
project| tree
.
├── mypkg
│ └── B.java
└── pkg
└── A.java
you should compile A
like this:你应该像这样编译
A
:
javac pkg/A.java
and B
with和
B
与
javac mypkg/B.java
you should do this from the project directory.您应该从项目目录执行此操作。 After you compile, the directory structure looks like this:
编译后,目录结构如下:
project| tree
.
├── mypkg
│ ├── B.class
│ └── B.java
└── pkg
├── A.class
└── A.java
BTW, you have a syntax error in your code, should be obj.printer();
顺便说一句,您的代码中有语法错误,应该是
obj.printer();
instead of A.printer();
而不是
A.printer();
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.