Okay, so I'm working on a battleship game, and I added these two tables which are throwing all sorts of errors, like:

  • Illegal Start of Expression,
  • Not a Statement,
  • ';' expected,
  • ']' expected,
  • <identifier> expected.

I have no idea why... Help, please?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class PlayerControl {
  private static int[] has;
  private static int[] placed;

  static ActionListener aListen = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      ...
    }
  };

  private static void menuAction(JMenuItem menuItem) {
    ...
  }

  private static void buttonAction(JButton button) {
    ...
  }

  static void placeShips() {
    has[10] = {5, 4, 4, 3, 3, 3, 2, 2, 2, 2};   //HERE
    placed[10] = {};                            //HERE
    JFrame instructionPlace;
//    instructionPlace.setVisible(true);
  }
}

You can't just make up your own syntax. Lines 24 and 25 don't correspond to any known Java syntax. It's difficult to guess what you may have intended, so it's hard to suggest a correction.
Check out whatever course materials you may have, or Google for relevant material.
This tutorial is a good place to start.

I just figured it out... I'm stupid. I had to have it as:

  ...
  private static int[] has;
  private static int[] placed = new int[10];

  ...

  int[] has = {5, 4, 4, 3, 3, 3, 2, 2, 2, 2};

And that was all I needed.

Be careful, that code doesn't do what you think it does.
Line 2 declares a static variable "has" that can refer to an array of ints. It's initial value is null.
Line 7 does not initialise that variable. It creates a new local variable, also called "has" and initialises it to an array with those values in it. If line 7 appears inside a method then the scope of the new "has" variable is just that method. As soon as the method terminates that array is garbage collected and all you are left with is the original "has" variable, which is still null. (Don't be embarrassed; this is a very common mistake.)

This article has been dead for over six months. Start a new discussion instead.