运行类的方法时,我得到一个“意外令牌:(”错误消息

问题描述

我是 Java 新手,我正在使用处理。我只是在学习如何使用类是 java,当我运行一个方法时,我收到了令人困惑的错误消息。错误消息是“意外令牌:(” p.setPieces(pawn,white); 行中的错误

这是我的代码

int ranks = 8;
int files = 8;
int spacing;

// set the values for all the pieces and colors
int empty = 0;
int pawn = 1;
int knight = 2;
int bishop = 3;
int rook = 4;
int queen = 5;
int king = 6;

int white = 8;
int black = 16;

Piece p = new Piece();
p.setPiece(pawn,white);

void setup() {
  size(600,600);
  spacing = width / ranks;
}
 
void draw() {
  background(0);

  // draw the board
  for (int i = 0; i < ranks; i++) {
    for (int j = 0; j < files; j++) {
      if ((i + j) % 2 == 0) {
        nostroke();
        fill(255);
        rect(i * spacing,j * spacing,spacing,spacing);
      } else {
        nostroke();
        fill(0);
        rect(i * spacing,spacing);
      }
    }
  }
}

然后在另一个文件中:

class Piece {

  // make variables for color and type of a piece
  int pieceType;
  int pieceColor;
  
  // set up type and color
  void setPiece(int Type,int Color) {
  
  pieceType = Type;
  pieceColor = Color;
  
  
  }
}

解决方法

正如 khelwood 和 luk2302 所提到的,只需将 p.setPiece(pawn,white); 移到 setup() 中(最好在 size() 之后):

int ranks = 8;
int files = 8;
int spacing;

// set the values for all the pieces and colors
int empty = 0;
int pawn = 1;
int knight = 2;
int bishop = 3;
int rook = 4;
int queen = 5;
int king = 6;

int white = 8;
int black = 16;

Piece p = new Piece();

void setup() {
  size(600,600);
  spacing = width / ranks;
  p.setPiece(pawn,white);
}
 
void draw() {
  background(0);

  // draw the board
  for (int i = 0; i < ranks; i++) {
    for (int j = 0; j < files; j++) {
      if ((i + j) % 2 == 0) {
        noStroke();
        fill(255);
        rect(i * spacing,j * spacing,spacing,spacing);
      } else {
        noStroke();
        fill(0);
        rect(i * spacing,spacing);
      }
    }
  }
}

class Piece {

  // make variables for color and type of a piece
  int pieceType;
  int pieceColor;
  
  // set up type and color
  void setPiece(int Type,int Color) {
  
  pieceType = Type;
  pieceColor = Color;
  
  
  }
}

当使用 "active" mode(例如 setup()/draw())时,您只能声明变量(在顶部),而不能直接在主代码块中使用它们。您需要在函数中引用它们。