我有这样的根目录:

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


Bicycle.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;
  }


BicycleMain.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());
        } }


我编译了Bicycle.java并成功,但是没有为BicycleMain.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和IT WORKS运行这些文件!但是为什么在CLI中编译时它不起作用?

最佳答案

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

例:

javac PathToSourceFile/FileName.java


如果源文件位于当前工作目录中,则无需提供path

其次,每当java遇到import abc.xyz.ClassName;时,它都会尝试针对abc/xyz/ClassName或当前工作目录解析classpath

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

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

javac -cp ../ BicycleMain.java


并且应该编译,因为类路径将设置为包含载具的目录(../)。这将解决您的Bicycle类。

然后使用

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

关于java - Javac“找不到符号”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61524129/

10-09 00:36