我正在写一个程序,用"O“来显示灯的电平,但当我编译时,它显示”找不到符号“,我声明了”消息“和”亮度“,还有什么我遗漏的东西要声明吗?类灯和类TestLamp我保存在不同的文件中,当我编译灯时,它没有显示错误。但它在编译TestLamp时显示“找不到符号”
class Lamp {
// Sub-task 1: Declare and initialize data member with default value
int brightness=1;
// Sub-task 2: Define a method to indicate the brightness level of lamp
String getBrightness() {
String message = "";
while(brightness>0) {
brightness--;
message += "O";
}
return message;
}
// Sub-task 3: Define a method to update the brightness of the lamp
void setBrightness(int b) {
if(b<1 || b>5)
brightness=2;
else
brightness=b;
}
}
class TestLamp {
public static void main (String[] args) {
// Sub-task 4: Declare and create 3 lamp objects
Lamp lamp1,lamp2,lamp3;
// Sub-task 5: Adjust the lamp brightness according to the requirement
lamp1.setBrightness(3);
lamp2.setBrightness(10);
// Sub-task 6: Display the information of the created lamps
lamp1.getBrightness();
System.out.println("Lamp1"+lamp1.message);
lamp2.getBrightness();
System.out.println("Lamp2"+lamp2.message);
}
}发布于 2013-11-08 15:44:32
您只需创建引用Lamp lamp1,lamp2,lamp3;,而不是先创建任何对象create object,如下所示
Lamp lamp1=new Lamp();字符串消息的作用域在getBrightness()方法中,所以lamp1.message会给你一个错误
因此,要打印消息,可以在类级别定义String message,也可以使用lamp1.getBrightness()
请看下面的工作代码
class Lamp {
// Sub-task 1: Declare and initialize data member with default value
int brightness=1;
String message = "";
// Sub-task 2: Define a method to indicate the brightness level of lamp
String getBrightness() {
while(brightness>0) {
brightness--;
message += "O";
}
return message;
}
// Sub-task 3: Define a method to update the brightness of the lamp
void setBrightness(int b) {
if(b<1 || b>5)
brightness=2;
else
brightness=b;
}
}
class ddd {
public static void main (String[] args) {
// Sub-task 4: Declare and create 3 lamp objects
Lamp lamp1 = new Lamp();
Lamp lamp2=new Lamp();
// Sub-task 5: Adjust the lamp brightness according to the requirement
lamp1.setBrightness(3);
lamp2.setBrightness(10);
// Sub-task 6: Display the information of the created lamps
lamp1.getBrightness();
System.out.println("Lamp1"+lamp1.message);
lamp2.getBrightness();
System.out.println("Lamp2"+lamp2.message);
}
}发布于 2013-11-08 15:43:37
您使用了lamp1.message,但是在Lamp类中没有message字段。
此外,您没有初始化Lamp的实例,这将导致另一个编译时错误。(感谢JasonC,我太习惯IDE了,以至于我忘记了基本的东西)。
发布于 2013-11-08 15:44:55
您还没有实例化您的lamp对象,并且您的Lamp类缺少message字段
https://stackoverflow.com/questions/19853863
复制相似问题