0

Hey all. I'm in the process of learning Java in my spare time, and I've bumped into a problem that I'm having a hard time wrapping my head around. I'm writing a small game (currently little more than an animation) involving a handful of blocks moving on-screen. I've created a subclass of JPanel to define GUI content (which would later be invoked in either an applet or stand-alone program), and all the GUI components are defined therein as nested classes. My question involves an "<identifier> expected" error at the constructor for one of these nested classes. Visually, this code looks similar to constructors made for other classes, and I think that's what's throwing me off. Here's the whole class:

private class NPCBlock
{
 int x, y, o;
 boolean isMovingNegative;

 NPCBlock(int x, y, o)
 {
  x = x;
  y = y;
  o = o;
  isMovingNegative = (Math.random() < 0.5);
 }

 void update()
 {
  if (isMovingNegative)
  {
   if (no == 1)
    x -= 15;
   else
    y -= 15;
  }
  else
  {
   if (no == 1)
    x += 15;
   else
    y += 15;
  }

  if (((x-30) < 0) | ((y-30) < 0))
   isMovingNegative = false;

  else if (((x+30) > width) | ((y+30) > height))
   isMovingNegative = true;
 }

 void draw(Graphics g)
 {
  g.setColor(Color.RED);
  g.fillRect(x-15, y-15, 30, 30);
 }
}

and this is an example of the constructor call: npc1 = new NPCBlock(width/2, height*.25, 1); The command line error message is:

BlockGamePanel.java:175: <identifier> expected
NPCBlock(int x, y, o)
^
BlockGamePanel.java:175: <identifier> expected
NPCBlock(int x, y, o)
^
2 errors

All instances of NPCBlock are initialized in the enclosing class. Does anyone see what I'm doing wrong? Should I have posted more of the code?

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by SavnetSinn
0
NPCBlock(int x, int y, int o) {
		this.x = x;
		this.y = y;
		this.o = o;
	}

Adjust your constructor as above. You have 2 issues:
1) you need to declare a type for each of the incoming parameters
2) parameters have precedence over global variables (e.g. this.x) within a constructor or method, so by do "x = x", you are telling the compiler to make the parameter equal itself, not the global variable as intended. To override this, add the object identifier in this case "this".

0

Also, look into the Random class; it has more flexibility than Math.random();

For instance, you can do: int i = new Random().nextInt(10); // gives a random between 0 and 9

0

Thank you. 'This' solved my problem, and you helped fix my misunderstanding about formal parameter definitions. It's much appreciated.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.