Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have got some code and it all seems to work apart from one error that appears. This stops the whole program running. Please could you have a look at the code and see what the issue is. This is a space invaders game and this is the class that contains the 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);
}
}
}
}
}
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "}" to complete MethodBody
at Alien.main(Alien.java:3)
You seem to be mis-understanding the basics of Java syntax. Specifically, you cannot define your class's members and methods inside main() the way you are attempting to do:
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
To get this to compile, you need to close main() and delete all the extra } you have at the end of your code:
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
You'll also need to add some code to main() before your program actually does anything.
I would suggest that before you continue your current program you read some of the excellent tutorials online. A good place to start is The Java™ Tutorials on the oracle website.
Look at the Trails Covering the Basics section and work your way through Getting Started and Learning the Java Language before doing anything else.
Related
how can I use the constructor from another class in java to make an object through a method in separate class. For example below is a constructor in a player class
public class Player extends Entity {
public Player(int maxEnergy, int x, int y) {
this.maxEnergy = maxEnergy;
this.energy = maxEnergy;
carryingGhost = false;
xPos = x;
yPos = y;
}
Which I want to use and create objects (player) through a method called
private Player createPlayer() {
and the above method is in separate class as
public class GameEngine {
**The method must return a Player object that represents the player in the
game. it must set the maxEnergy for the player, and the
X and Y positions corresponding to a tile position in the current level.
I have tried to initialize player within method with parameters and
without parameters as**
Player player = new Player(int maxEnergy, int x, int y);
this.player.getEnergy();
this.player.getMaxEnergy();
this.player.setPosition(x, y);
return player;
}
But it give errors.Any help will be appreciated.I am quite close to assume its not possible to have created objects like this.
below I share the complete game engine which is working with other classes as well .
import java.awt.Point;
import java.util.ArrayList;
import java.util.Random;
public enum TileType {
WALL, FLOOR1, FLOOR2, BANK, BREACH, DOOR;
}
public static final int LEVEL_WIDTH = 35;
public static final int LEVEL_HEIGHT = 18;
private Random rng = new Random();
private int levelNumber = 1; //current level
private int turnNumber = 1;
private GameGUI gui;
private TileType[][] level;
private ArrayList<Point> spawnLocations;
private Player player;
private Ghost[] ghosts;
public GameEngine(GameGUI gui) {
this.gui = gui;
}
private TileType[][] generateLevel() {
//YOUR CODE HERE
return null; //change this to return the 2D arrayof TileType
//values that you create above
}
private ArrayList<Point> getSpawns() {
ArrayList<Point> s = new ArrayList<Point>();
// YOUR CODE HERE
return s;
}
private Ghost[] addGhosts() {
//YOUR CODE HERE
return null; //change this to return an array of ghost objects
}
**/**
* Creates a Player object in the game. The method instantiates
* the Player class and assigns values for the energy and position.
* The first version of this method should use fixed a fixed position
for the player to start, by setting fixed X and Y values when calling
the constructor in the Player class. The second version of this method
should use the spawns ArrayLis to select a suitable location to spawn
the player and removes the Point from the spawns ArrayList. This will
prevent the Player from being added to the game inside a wall, bank or
breach for example.
#return A Player object representing the player in the game
*/**
private Player createPlayer() {
//YOUR CODE HERE
return null; //change this to return a Player object
}
public void movePlayerLeft() {
}
public void movePlayerRight() {
}
public void movePlayerUp() {
}
public void movePlayerDown() {
}
private void hitGhost(Ghost g) {
}
private void moveGhosts() {
}
private void moveGhost(Ghost g) {
}
private void cleanDefeatedGhosts() {
}
private void nextLevel() {
}
private void placePlayer() {
}
public void doTurn() {
cleanDefeatedGhosts();
moveGhosts();
gui.updateDisplay(level, player, ghosts);
}
public void startGame() {
level = generateLevel();
spawnLocations = getSpawns();
ghosts = addGhosts();
player = createPlayer();
gui.updateDisplay(level, player, ghosts);
}
}
I have used below method and its not showing error so far.
private Player createPlayer() {
int energy=player.getEnergy();
int maxEnergy=player.getMaxEnergy();
int xPos=player.xPos;
int yPos=player.yPos;
return new Player(maxEnergy,xPos,yPos);
}
The following should do it:
private Player createPlayer() {
int defaultMaxEnergy = 10; // Whatever value it should have
int initialX = 1; // Whatever value it should have
int initialY = 1; // Whatever value it should have
return new Player(defaultMaxEnergy, initialX, initialY);
}
Since the values are not in your descriptions I just selected a random number but you can pick whatever integers you want and that makes sense.
Does something like this work for your case?
public class GameEngine {
private Player createPlayer() {
return new Player(1,2,3);
}
}
Add a default no-args constructor in the player class. Once you create a constructor with Arg, java will not auto provide default one.
You have already declared Player
private Player player;
So you must not try to reinitialize using same variable name, rather
private Player createPlayer() {
Player newPlayer = new Player();
// set the different props of the Player obj
return newPlayer ;
}
What is the error which you are facing ? Can you share that ?
I am trying to create a console chess game.
I have Square class and my Chessboard have 64 Square objects. Also some of these squares have Piece object. How can i add these Piece objects into the Square Objects?*
public class Square {
int column;
int row;
Piece piece;
Square(){
}
public void setRow(int row) {
this.row=row;
}
public void setColumn(int col){
this.column=col;
}
#Override
public String toString() {
// TODO Auto-generated method stub
if(1< row && row <6)
return " ";
return super.toString();
}
}
public void setPiece(Piece piece) {
this.piece = piece;
}
Adding this to your class lets you set a piece for each square. You can also define the piece in the square's constructor as this quarantees that a square always has a defined piece.
You can add these useful methods to your Square class in order to set the various pieces between all the squares you want.
/**
* #param piece to set on the actual square.
*/
public void setPiece(Piece piece) {
this.piece = piece;
}
/**
* Removes the actual piece on the square, if it exists.
*/
public void removePiece() {
if(piece != null)
piece = null;
}
/**
* #param square where to move the piece on the actual square.
* #return true if the piece were moved correctly, false otherwise.
* e.g. of a false return is when the piece on the actual square is not present, in other words, it is null.
*
* ATTENTION: Obviously the moved piece is removed from the actual square.
*/
public boolean movePiece(Square square) {
if(piece != null) {
square.setPiece(piece);
removePiece();
return true;
} else
return false;
}
Basically I made I class to extend the grid to 11 by 11, the constructor is being called however its not changing the grid. Any input or information on why would be greatly appreciated. I've posted my code below:
import info.gridworld.actor.*;
import info.gridworld.grid.BoundedGrid;
public class ChangeGrid extends ActorWorld{
private static final int SIZEROW = 11;
private static final int SIZECOL = 11;
public ChangeGrid()
{
super(new BoundedGrid<Actor>(SIZEROW, SIZECOL));
System.out.println("test");
}
}
import info.gridworld.actor.Bug;
public class XBug extends Bug {
/**
* A <code>BoxBug</code> traces out a square "box" of a given size. <br />
* The implementation of this class is testable on the AP CS A and AB exams.
*/
private int steps;
private int sideLength;
private int x = 0;
private static ChangeGrid object = new ChangeGrid();
/**
* Constructs a box bug that traces a square of a given side length
* #param length the side length
*/
public XBug(int length)
{
steps = 0;
sideLength = length;
}
/**
* Moves to the next location of the square.
*/
public void act()
{
if (steps < sideLength && canMove())
{
if(x==0)
{
turn();
}
move();
steps++;
x++;
}
else
{
turn();
steps = 0;
}
}
}
Your constructor is not being called when you create the world. You are calling it inside of an Actors class, then you don't even call the .show() method. You just need to change your runner class to call ChangeWorld instead of ActorWorld.
Here's an example for your code.
public class Runner
{
public static void main(String[]args)
{
ChangeWorld world = new ChangeWorld();
XBug bug = new XBug();
world.add(bug);
world.show();
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
i have 4 classes (Core, GameMain, Spriter, Character)
- GameMain extends core (core >> GameMain)
- Character extends Spriter (Spriter >> Character)
I get a NullPointerException if i call the - b.get...() - Methods without overriding them in Character (they are originally inside Spriter, i call them from GameMain through Character).
i make objects of Character inside Core and put it in an ArrayList
public abstract class Core {
ArrayList<Character> mon = new ArrayList<Character>();
void gameloop(){
while(running){
//some code
while(mon.size() < 2){
mon.add(new Character(blk_1,5,1));// Character(Spriter, Long, Long){}
}
draw(g);
}
}
}
then inside GameMain i call a Method that is originally inside Spriter but i call it through Character.
public class GameMain extends Core{
public void draw(Graphics2D g){
for(Character b : mon){ //mon is the ArrayList<Character>
if(test.getCoordY() <= b.getCoordY() - (b.getHeight()/2)){ //<<<< NullPointerException caused by these two Methods , test is a Spriter class
g.drawImage(chChange(), Math.round(test.getX()), Math.round(test.getY()), test.getWidth(), (test.getHeight()), null);
g.drawImage(b.getImage(), Math.round(b.getX()), Math.round(b.getY()), null);
}else {
g.drawImage(b.getImage(), Math.round(b.getX()), Math.round(b.getY()), null);
g.drawImage(chChange(), Math.round(test.getX()), Math.round(test.getY()), null);
}
}
}
}
Here is the Spriter's Method, unless i override it i will get the error.
public class Spriter {
Spriter(Image i){
this.i = i;
scenes = new ArrayList();
}
Spriter(){
scenes = new ArrayList();
start();
}
public int getHeight(){
return i.getHeight(null);
}
public float getCoordY(){
float cy;
cy = y + i.getHeight(null); //<<<< NullPointerException happens here, Image i;
return cy;
}
public void setX(float x){
this.x = x;
}
public void setY(float y){
this.y = y;
}
// other similar Methods but no problem with them
//-------------------------------------- Animation Part ----------------------------------------------
public synchronized void addScene(Image i,long t){
total_t+=t;
scenes.add(new oneScene(i, total_t));
}
//start animation
public synchronized void start(){
mov_time = 0;
scn_indx = 0;
}
// get current scene
public synchronized Image getAnimeImage(){
if(scenes.size()==0){
return null;
}else{
return getScene(scn_indx).pic;
}
}
//get the scene
private oneScene getScene(int x){
return (oneScene)scenes.get(x);
}
private class oneScene{
Image pic;
long endTime;
public oneScene(Image pic, long endTime){
this.pic = pic;
this.endTime = endTime;
}
}
}
it would work if i do this :
public class Character extends Spriter{
public Character(Spriter s, long health, long power) {
this.s = s;
this.health = health;
this.power = power;
s.setX(randomY());
s.setY(randomY());
}
public float getCoordY(){
return s.getCoordY();
}
public float getHeight(){
return s.getgetHeight();
}
//some other methods for health and power
}
but can it work if i do this (it is already givinng the error but how to avoid it) :
public class Character extends Spriter{
public Character(Spriter s, long health, long power) {
this.s = s;
this.health = health;
this.power = power;
s.setX(randomY()); //setting x for the dynamiclly generated Character Object
s.setY(randomY()); // same for y
}
//some methods for power and health
}
as setting x,y for test (its a sprite and working very good)
public class GameMain extends Core{
public void init(){
test.setX(500); test.setY(488);
}
public void draw(Graphics2D g){
//the above code
}
}
i dont see the point of overriding them if they will be exactly the same.
Your problem is that when you create a Character, you're calling the no-arg constructor of Spriter, instead of the one with an Image argument. That means that your image is never getting set; which is why you have the null pointer exception.
You should probably add an Image to the constructor arguments of Character, and pass this along to the superclass constructor, like this.
public Character(Spriter s, long health, long power, Image img) {
super(img);
// and so on.
#ElliottFrisch - I apologise if that is what you were trying to say with your answer. I don't mean to duplicate; I just wasn't quite sure whether that is what you meant. In any case, this is definitely the problem.
I believe your problem is that your class Character is-a Spriter and has-a Spriter (and probably shouldn't "have-a" Spriter but I can't tell because you didn't post all of your code). You never initialized the super instance of your Character.
public class Character extends Spriter{
public Character(Spriter s, long health, long power) {
// super(health, power); // <-- Speculation, no constructors shown in your code.
this.s = s;
this.health = health;
this.power = power;
super.setX(randomY()); //<-- set the super value
super.setY(randomY()); //<-- again.
// s.setX() // <-- not sure, why do you have s?
}
So what im trying to do is to call an external method upon an object, its a bit trickier than I expected and am having problems properly implementing it.
The method is:
attack(Player victim)
The method needs to call a hit() method on an object; then if the hit() method was successful (test this through a boolean?):
use an if statement to call a damage() method upon the object to determine the damage
call takeDamage() upon (PlayerVictim) to inflict the damage.
Here's the player class that ive coded so far; the attack() method is at the bottom.
My main question is how to use an external method(s) damage() on the currentWeapon and takeDamage() on Player Victim
public class Player
{
private String myPlayerName;
private Weapon myWeapon;
private int myCurrentHealth;
private int myMaxHealth;
private int myNumPotions;
/**
* Constructor initializing class Player
* Parameters of the player should be:
* player name, players initial health, the players weapon.
*/
public Player(String myPlayer, int initialHealth, Weapon currentWeapon) {
myPlayerName = myPlayer;
this.myWeapon = currentWeapon;
myMaxHealth = 30;
myCurrentHealth = initialHealth;
myNumPotions = 0;
}
/**
* Attack method which attacks opposing player
* with current equipped weapon.
*/
public void attack(Player victim) {
currentWeapon.hit();
if (boolean currentWeapon.hit() = true) {
currentWeapon.damage(int dam);
return dam;
}
Player victim.takeDamage(int damage);
}
}
and the weapon class:
import java.util.Random;
public class Weapon
{
private int myHitProb;
private int myMaxDamage;
private Random myRNG;
/**
* Create a new weapon with a hit probability and damage
*/
public Weapon(int hitProb, int damage) {
myHitProb = hitProb;
myMaxDamage = damage;
myRNG = new Random();
}
public boolean hit() {
int r = myRNG.nextInt(100);
if (r < myHitProb) {
return true;
}
else {
return false;
}
}
public int damage() {
int dam = myRNG.nextInt(myMaxDamage) + 1;
return dam;
}
}
Your attack() method may be many things, but compilable java it is not.
Perhaps this is what you meant:
public void attack(Player victim) {
if (currentWeapon.hit()) {
victim.takeDamage(currentWeapon.damage());
}
}
Try to remember this guideline: If it seems hard, you're probably doing it the wrong way (unless you're working on the Mars Lander program :) )