-2

Why is it giving an error in the line treasureLocations[] = new Coord(rows, cols); of the concstructor?

public class TreasureMap{
    int rows, cols;     // How big is the treasure map
    Coord [] treasureLocations; // The locations of treasures

    Scanner kbd = new Scanner(System.in);
  // Prompt the user for info on the treasure map and then create it
  // COMPLETE THIS METHOD
  public TreasureMap(){

      System.out.println("Enter the map size (2 ints): ");
      rows = kbd.nextInt();
      cols = kbd.nextInt();
      treasureLocations[] = new Coord(rows, cols);




public class Coord {
  public final int row;
  public final int col;

  // Constructor, 
  public Coord(int ir, int ic){
    this.row = ir;
    this.col = ic;
  }
Inferno
  • 3
  • 1
  • 6

2 Answers2

2
treasureLocations[] = new Coord(rows, cols);

This line isn't valid syntax. You need to assign the new object to a position inside the array, by putting an int value inside the square brackets. Like so:

int position = 0;
treasureLocations[position] = new Coord(rows, cols);

You also need to initialize the array. Looking up at the top of your program, you've declared it but not assigned it to anything, so at runtime you'll get a null pointer exception. Something like this:

Coord [] treasureLocations = new Coord[someNumber]; // The locations of treasures
Esoteric Screen Name
  • 5,913
  • 4
  • 27
  • 38
  • What do you mean by "to assign the new object to a position inside the array, not the array itself" ? – Inferno Mar 08 '15 at 02:05
  • @Inferno Something like `treasureLocations[0] = new Coord(rows, cols);`. You need to put an int inside the square brackets to specify the position inside the array. Using an int variable is OK. You should also be careful not to try and assign a position >= array.length or you'll get an error. – Esoteric Screen Name Mar 08 '15 at 02:09
0

after new Coord(..., ...); put "}" on the line afterwards.

And you are trying to make an array "[]" only one Coord.