1

昨天我开始从 Oracle 网站学习 Java 教程,但第一个程序(Bicycle :) 有问题。我只用一个类(class Bicycle)创建了项目,然后打开新项目并编写了创建两个Bicycle对象并调用它们的方法的类。当我尝试构建项目时收到错误消息:

"error: cannot find symbol Bicycle bike1=new Bicycle(); symbol: class Bicycle location: class BicycleDemo".

我尝试右键单击库并添加项目 - 没用,尝试在当前项目中创建新类(具有相同的内容) - 没用。该怎么办?

package bicycledemo;
/**
*
* App witch simulates using of Bicyle class.
*/
public class BicycleDemo {
import Bicycle;  
public static void main(String[] args) {
    Bicycle bike1=new Bicycle();
    Bicycle bike2=new Bicycle();

    bike1.changeCadence(34);
    bike1.increaseSpeed(3);
    bike1.changeGear(2);
    bike1.printStates();

    bike2.changeCadence(3);
    bike2.increseSpeed(12);
    bike2.printStates();
}
}

而且我在项目 BicycleDemo 的库中也有整个 C:\Users\nojo\Documents\NetBeansProjects\Bicycle 文件。Bicycle.java 的代码:

public class Bicycle {
int cadence=0;
int speed=0;
int gear=1;

void changeCadence(int newValue){
cadence=newValue;
}
void increaseSpeed(int increase){
speed=speed+increase;
}
void applyBreaks(int decrease){
speed=speed-decrease;
}
void changeGear(int gearNumber){
gear=gearNumber;
}
void printStates(){
System.out.println("cadence:" + cadence + "speed:" + speed +
        "gear:" + gear);
}
}
4

1 回答 1

2

Looks like your import statement is in the wrong location. It should be below the package name and before the the beginning of the clas definition.

package bicycledemo;
import <yourpackagename>.Bicycle;

You can do this where you are currently declaring bike1 but you have to use thepackage name and class name when you do.

<yourpackagename>.Bicycle bike1 = new Bicycle();

What you're reading is a tutorial on the "concepts" of OO programming and not an in depth tutorial, Packages are explained further along in the tutorial.

Your problem is probably you made two projects, one has the bicycle class and one has the bicycledemo class, correct? If that is correct then in both projects your class is in the default package, which is bad. To fix your problem, create a new project with both classes in the same project.

于 2012-05-16T19:38:11.137 回答