为什么Java如果以正确的方式放置大括号会给出错误?
Java是否决定何时需要放置大括号,何时不需要也可以正确放置折边? 我正在编译一个关于机器人游戏的项目,但如果它们是以正确的方式编写的,则更改大括号顺序会给出错误。我插入了两种不同类型的代码的代码,但只有正确的:为什么Java如果以正确的方式放置大括号会给出错误?
1)
public class Robot {
//In Java, Class Variables should be private so that only its methods can change them.
private int centerX=100;
private int centerY=382;
private boolean jumped=false;
private int speedX=0;
private int speedY=1;
public void update(){
//Moves Character or Scrolls Background accordingly.
if(speedX<0)
centerX+=speedX;
else if(speedX==0)
System.out.println("Do not scroll the background.");
}
// Updates Y Position
if(centerY + speedY >=382)
centerY=382;
else
centerY+=speedY;
//Handles Jumping
if (jumped==true)
speedY+=1;
if(centerY+speedY>=382){
centerY=382;
speedY=0;
jumped=false;
}
}
2)
public class Robot {
//In Java, Class Variables should be private so that only its methods can change them.
private int centerX=100;
private int centerY=382;
private boolean jumped=false;
private int speedX=0;
private int speedY=1;
public void update(){
//Moves Character or Scrolls Background accordingly.
if(speedX<0)
centerX+=speedX;
else if(speedX==0)
System.out.println("Do not scroll the background.");
// Updates Y Position
if(centerY + speedY >=382)
centerY=382;
else
centerY+=speedY;
//Handles Jumping
if (jumped==true)
speedY+=1;
if(centerY+speedY>=382){
centerY=382;
speedY=0;
jumped=false;
}
}
}
所以把所有的代码的方法更新()没有错误,而如果您将// Updates Y Position中的所有提示都忽略不计,编译器会发现错误。但从技术上讲应该没有错误吧?
编辑 第一个代码给出错误: Syntax error, insert "}" to complete ClassBody
对于任何代码得到执行 - 它必须是一个方法里面!如果代码不在方法或任何其他代码块中,那么它何时会执行? 一个类不是只执行类中的方法,块构造函数等。类的唯一目的是声明各种可执行块,如方法,块。 For more info you can visit this page
由于你在最后一条if语句中做了缩进,所以我相当确定你的意思是让代码块包含最后一条,如果在2. last if中。
这是该方法内的代码的一部分。
public void update(){
//Moves Character or Scrolls Background accordingly.
if(speedX<0)
centerX+=speedX;
else if(speedX==0)
System.out.println("Do not scroll the background.");
}
这部分是不是:
// Updates Y Position
if(centerY + speedY >=382)
centerY=382;
else
centerY+=speedY;
//Handles Jumping
if (jumped==true)
speedY+=1;
if(centerY+speedY>=382){
centerY=382;
speedY=0;
jumped=false;
}
允许在酒店外的方法和构造函数声明 唯一的东西是字段的声明。被允许在类级
是的,一个人已经给出了答案,但无论如何感谢。 – Pierfrank
任何仅声明。就像声明变量,方法等一样。您希望您的代码在数据上执行的所有工作必须始终在方法或构造函数内部之内。 因此,当您将if else条件放在方法之外时,Java不知道如何处理所有代码。
你得到了什么错误? – Pshemo
是的,试图把非声明语句放在类里面会给你一个错误。当你不希望在方法内部执行if(centerY + speedY> = 382)...时执行? – Dukeling
我已添加屏幕截图来向您显示错误 – Pierfrank