如何使用 vscode 将一个文件的 class 导入到 Java 中子文件夹中的另一个文件
How to import class of one file to another in a subfolder in Java using vscode
import mytest.Mypckg;
public class Learn {
public static void main(String[] args) {
System.out.println("Hello World");
Mypckg.show();
}
}
package mytest;
public class Mypckg {
public static void show(){
System.out.println("Good Moring");
}
}
两个文件都在相同的子文件夹名称 mytest 中
但是当我尝试 运行 main file => Learn 时,出现错误
“Learn.java:2:错误:找不到符号导入 mytest.Mypckg;”。我还尝试从 Learn 文件中删除 import mytest.Mypckg,因为两者都具有相同的包,但是当我编译时,出现“找不到符号 Mypckg”的错误。
我假设这两个文件都在名为 mytest
的 package/folder 中
你的代码似乎错过了下面添加的这一行
package mytest;//added line
//import mytest.Mypckg;
public class Learn {
public static void main(String[] args) {
System.out.println("Hello World");
Mypckg.show();
}
}
在一个案例中你是对的,我没有在主文件中提到包 mytest (Learn.java)。那是我的错,但是在我的计算机上,当我在两个文件中都提到 package mytest 时,我也收到了类似“找不到符号导入 mytest.Mypckg;” 的错误。
我终于找到了解决办法。实际问题是我在子文件夹 mytest 中使用编译方法。事实上,我试图通过在子文件夹之外获取 mytest 文件夹的路径来编译文件。但罪魁祸首是 else.I 在我的编译代码中没有使用 class 路径(即 -cp)。因此,要编译 vscode 中的包文件,我们必须转到父文件夹并键入以下代码。
javac -cp . mytest/Learn.java // compiler code with file path
还有运行我们必须使用的文件
java mytest.Learn // mytest is a subfolder (package folder) and learn is a main file
为了更好地说明我的同事们,我在下面附上了图片。我希望我的回答能帮助那些想用 vscode 中的包编译 java 代码的人
import mytest.Mypckg;
public class Learn {
public static void main(String[] args) {
System.out.println("Hello World");
Mypckg.show();
}
}
package mytest;
public class Mypckg {
public static void show(){
System.out.println("Good Moring");
}
}
两个文件都在相同的子文件夹名称 mytest 中 但是当我尝试 运行 main file => Learn 时,出现错误 “Learn.java:2:错误:找不到符号导入 mytest.Mypckg;”。我还尝试从 Learn 文件中删除 import mytest.Mypckg,因为两者都具有相同的包,但是当我编译时,出现“找不到符号 Mypckg”的错误。
我假设这两个文件都在名为 mytest
的 package/folder 中
你的代码似乎错过了下面添加的这一行
package mytest;//added line
//import mytest.Mypckg;
public class Learn {
public static void main(String[] args) {
System.out.println("Hello World");
Mypckg.show();
}
}
在一个案例中你是对的,我没有在主文件中提到包 mytest (Learn.java)。那是我的错,但是在我的计算机上,当我在两个文件中都提到 package mytest 时,我也收到了类似“找不到符号导入 mytest.Mypckg;” 的错误。
我终于找到了解决办法。实际问题是我在子文件夹 mytest 中使用编译方法。事实上,我试图通过在子文件夹之外获取 mytest 文件夹的路径来编译文件。但罪魁祸首是 else.I 在我的编译代码中没有使用 class 路径(即 -cp)。因此,要编译 vscode 中的包文件,我们必须转到父文件夹并键入以下代码。
javac -cp . mytest/Learn.java // compiler code with file path
还有运行我们必须使用的文件
java mytest.Learn // mytest is a subfolder (package folder) and learn is a main file
为了更好地说明我的同事们,我在下面附上了图片。我希望我的回答能帮助那些想用 vscode 中的包编译 java 代码的人