在Java中编译实例方法时出现语法错误
我已经编写了一段代码,声明了三个实例变量和两个实例方法。但是,当我运行程序时,我在checkTemperature方法中收到一个语法错误。我已经检查了我的语法是否有任何缺少/过度使用的大括号、分号等,但是代码看起来很好。我不知道我为什么会收到这个错误,有人能帮我解决这个问题吗?下面是我的代码在Java中编译实例方法时出现语法错误,java,Java,我已经编写了一段代码,声明了三个实例变量和两个实例方法。但是,当我运行程序时,我在checkTemperature方法中收到一个语法错误。我已经检查了我的语法是否有任何缺少/过度使用的大括号、分号等,但是代码看起来很好。我不知道我为什么会收到这个错误,有人能帮我解决这个问题吗?下面是我的代码 public class volcanoRobots { /** * @param args */ public static void main(String[] arg
public class volcanoRobots {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* declared instance variables status, speed,temperature
*/
String status;
int speed;
float temperature;
/*
* create first instance method checkTemperature
*/
void checkTemperature(){
if (temperature > 660){
status = "returning home";
speed = 5;
}
}
/*
* create second instance method showAttributes
*/
void showAttributes(){
System.out.println("Status: " + status);
System.out.println("Speed: " + speed);
System.out.println("Temperature: " + temperature);
}
}
}
在另一个方法中不能有一个方法。将该方法移动到类的主体中,您的代码应该可以编译。而且,您的实例变量实际上不是实例变量;它们是
main
方法的局部变量。使用适当的可见性修饰符,将它们移动到类的主体中;我建议把它们变成私人的
还有几件事:
- 还可以为方法添加可见性修饰符。同样,在这种情况下,我建议
。没有任何修饰符,它们是包私有的,这可能不是您想要的private
- 遵循Java命名约定;您的类应命名为
。类名称是PascalCase,而变量和方法名称是camelCase类
public class VolcanoRobots {
/*
* declared instance variables status, speed,temperature
*/
private String status;
private int speed;
private float temperature;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/*
* create first instance method checkTemperature
*/
private void checkTemperature(){
if (temperature > 660){
status = "returning home";
speed = 5;
}
}
/*
* create second instance method showAttributes
*/
private void showAttributes(){
System.out.println("Status: " + status);
System.out.println("Speed: " + speed);
System.out.println("Temperature: " + temperature);
}
}
不能在方法中定义方法。只需将这些方法移到
main
之外。它们不是实例变量,而是局部变量。非常感谢您的支持。但是,当我使用您编辑的代码运行要编译的代码时,不会显示任何内容。为什么会这样?