【问题标题】:I cannot import class of one file to another in a subfolder in Java using vscode我无法使用 vscode 将一个文件的类导入 Java 子文件夹中的另一个文件
【发布时间】:2022-01-01 07:15:01
【问题描述】:

如何在子文件夹中导入不同目录中的类?

我是 Java 编程语言的新手,我想通过导入他们的包来使用其他目录中的类,但我做不到!!。

我有一个名为 Car 的类。

package ir.tclas.clasor.models;

public class Car {
private String Models;
private String Name;
private String Color;
private Integer weigth;


public void setWeigth(Integer weigth) {
    if (weigth > 50)
        this.weigth = 45;
    else {
        this.weigth = weigth;
    }

}

public String getModels() {
    if (Models == null)
        Models = "NO_Name";
    return Models;
}


  public void horn() {
  System.out.println("Beeeeeep!!!");
  }
}

现在我想从 MainApp 导入汽车

  package ir.tclas.clasor;

  import ir.tclas.clasor.models.Car;

  public class MainApp {
  public static void main(String[] args) {

    Car bmw = new Car();

    bmw.setName("BMW");
    bmw.setColor("Blue");
    bmw.setWeigth(55);

    bmw.horn();
    System.out.println(bmw.getName());
    System.out.println(bmw.getModels());
    System.out.println(bmw.getColor());
    System.out.println(bmw.getWeigth());
 }
}

这是我运行代码后的输出:

 PS E:\java_pj\001\demo> cd 
 "e:\java_pj\001\demo\src\main\java\ir\tclas\clasor\" ; if ($?) { 
 javac MainApp.java } ; if ($?) { java MainApp.java }
 MainApp.java:4: error: package ir.tclas.clasor.models does not exist
 import ir.tclas.clasor.models.Car;
                         ^    
 MainApp.java:9: error: cannot find symbol
    Car bmw = new Car();
    ^
 symbol:   class Car
 location: class MainApp
 MainApp.java:9: error: cannot find symbol
    Car bmw = new Car();
                  ^
 symbol:   class Car
 location: class MainApp
 3 errors

 PS E:\java_pj\001\demo\src\main\java\ir\tclas\clasor>

谁能告诉我怎么做?

【问题讨论】:

  • 欢迎来到 Stack Overflow。我强烈建议您使用 tour 了解 Stack Overflow 的工作原理并阅读 How to Ask。这将帮助您提高问题的质量。 切勿发布代码的图片。将您的代码发布为文本并将其格式化为代码。

标签: java maven class visual-studio-code package


【解决方案1】:

Code Runner 在编译 .java 文件时不包含包,这就是发生错误的原因,您应该手动更改 Settings.json 中的命令:

"code-runner.executorMap": {
    "java": "cd e:/java_pj/001/demo/src/main/java && javac ir/tclas/clasor/models/Car.java && javac ir/tclas/clasor/$fileName && java ir/tclas/clasor/$fileNameWithoutExt",       
}

或者您可以直接禁用扩展 Code Runner 并通过 Java Extension 运行您的项目。在Car.java中添加getter和setter后,你的代码运行良好,没有报错:

【讨论】:

    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多