我有一些代码,但似乎除了出现的一个错误外,它们都有效。这会停止整个程序的运行。请问您能看一下代码,看看问题是什么。这是一个太空入侵者游戏,这是包含public static void main的类。
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25;
public static int ALIEN_WIDTH = 15;
private int leftPosition = 0;
private int heightPosition = 0;
private boolean hitState = false;//Whether this alien has already been shot
private Image alienImage = null;
SpaceInvaders spaceInvaders = null;
/**
*
*/
public Alien(Image ai, SpaceInvaders si) {
alienImage = ai;
spaceInvaders = si;
}
/**
* Returns whether ythe alien had been hit
*/
public boolean hasBeenHit() {
return hitState;
}
/**
* Check if a shot fired hit an alien
*/
public boolean hitAlien(int x, int y) {
//Is the alien currently alive?
if (hitState) {
//If it's alreay been shot then return false;
return false;
}
//First lets check the X range
if ((x >= leftPosition) && (x <= (leftPosition+ALIEN_WIDTH))) {
//X is ok, now lets check the Y range
if ((y >= heightPosition) && (y <= (heightPosition+ALIEN_HEIGHT))) {
//We shot an alien!
hitState = true;
return true;
}
}
return false;
}
/**
* Set the position of the alien on the screen
*/
public void setPosition(int x, int y) {
leftPosition = x;
heightPosition = y;
}
/**
* Returns the current x position of the alien
*/
public int getXPos() {
return leftPosition;
}
/**
* Returns the current x position of the alien
*/
public int getYPos() {
return heightPosition;
}
/**
* Draw the image of the Alien
*/
public void drawAlien(Graphics g) {
if (!hitState) {
g.setColor(Color.red);
g.fillRect(leftPosition, heightPosition, ALIEN_WIDTH, ALIEN_HEIGHT);
}
}
}
}
}
错误是:
线程“main”中的异常java.lang.Error:未解决的编译问题: 语法错误,插入“}”以完成MethodBody
at Alien.main(Alien.java:3)
答案 0 :(得分:3)
您似乎错误地理解了Java语法的基础知识。具体而言,您无法按照您尝试的方式在 main()
内定义班级的成员和方法:
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25; // you can't put this here
public static int ALIEN_WIDTH = 15; // you can't put this here
private int leftPosition = 0; // you can't put this here
private int heightPosition = 0; // you can't put this here
//etc
要进行编译,您需要关闭main()
并删除代码末尾的所有额外}
:
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25;
public static int ALIEN_WIDTH = 15;
//etc
在程序实际执行任何操作之前,您还需要向main()
添加一些代码。
我建议您在继续当前的课程之前,先在线阅读一些优秀的教程。一个好的起点是oracle网站上的The Java™ Tutorials。
查看 Trails Covering the Basics 部分,然后在完成任何其他工作之前,逐步完成Getting Started和Learning the Java Language。