Javac “找不到符号”

我有这样的根目录:

├── classes
└── src
    └── vehicles
        ├── Bicycle.java
        └── BicycleMain.java

自行车.java

package vehicles;

public class Bicycle {

  public int cadence;
  public int gear;
  public int speed;

  public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
  }

  public void setCadence(int newValue) {
      cadence = newValue;
  }
  public void setGear(int newValue) {
    gear = newValue;
  }
  public void setSpeed(int newValue) {
    speed = newValue;
  }
  public int getGear() {
    return gear;
  }
  public int getCadence() {
    return cadence;
  }
  public int getSpeed() {
    return speed;
  }
  public void applyBrake(int decrement) {
    speed -= decrement;
  }
  public void speedUp(int increment) {
    speed += increment;
  }

自行车主.java

package vehicles; import vehicles.*;

public class BicycleMain {
        public static void main (String args[]){
        Bicycle Bike = new Bicycle(10, 20, 1);
        System.out.println("We have a new bicycle with speed = " +Bike.getSpeed()+", cadence = "+Bike.getCadence()+", gear = "+Bike.getGear());
        } }

我编译了Bike.java和成功,但不是为BikeMain.java:

symbol  : class Bicycle
location: class vehicles.BicycleMain
    Bicycle Bike = new Bicycle(10, 20, 1);
    ^
src/vehicles/BicycleMain.java:6: cannot find symbol
symbol  : class Bicycle
location: class vehicles.BicycleMain
    Bicycle Bike = new Bicycle(10, 20, 1);
                       ^
2 errors

我尝试用Netbeans运行这些文件,它的工作原理!但是为什么当我在CLI中编译时它不起作用?


答案 1

首先,要使用 Java 源文件编译,您需要指定要显式编译的文件。javac

例:

javac PathToSourceFile/FileName.java

您不需要提供 源文件是否在当前工作目录中。path

其次,每当遇到java时,它就会尝试解析与当前工作目录相关的问题。import abc.xyz.ClassName;abc/xyz/ClassNameclasspath

因此,如果您在车辆文件夹中并编译代码,则不会编译,因为它将在文件夹车辆内查找文件夹车辆(不存在!

但是,您可以在车辆文件夹内执行此操作

javac -cp ../ BicycleMain.java

并且它应该编译,因为类路径将被设置为包含车辆的目录()。这将解析您的类。../Bicycle

然后使用

java -cp ../ vehicles/BicycleMain以运行。


答案 2

尝试从命令行中删除该行,并在命令行中使用javac进行编译。import vehicles.*;BicycleMain.java

顺便说一句,发生这种情况是因为当您在javac中编译时,您在文件夹中,并且您编写了一个语句,这意味着编译器在文件夹中有另一个文件夹,而这里的情况并非如此。vehiclesimport vehicles.*;BicycleMain.javavehiclesvehicles