【问题标题】:When running a method of a class I get a 'unexpected token: (' error message运行类的方法时,我收到“意外令牌:(”错误消息
【发布时间】:2021-09-08 02:39:54
【问题描述】:

我是 java 新手,我正在使用处理。我只是在学习如何使用类是 java,当我运行一个方法时,我收到了令人困惑的错误消息。错误消息是'unexpected token: (' 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, j * spacing, 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;
  
  
  }
}

【问题讨论】:

  • 你不能在课堂上直接调用p.setPiece(pawn, white);。它应该在方法或构造函数或初始化块中。
  • 而且void setup() { 永远不会关闭 - 或者为时已晚,您不能在其中包含void draw() {
  • 它不在一个类中它在主文件中该类在另一个文件中。
  • void setup 没有关闭,因为我在复制时打错了,现在你指出了我已修复它
  • p.setPiece(pawn, white); 不能在 void setup() { 之前,不能在方法之外(正如 khelwood 已经说过的)

标签: class methods processing


【解决方案1】:

正如 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, j * spacing, 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())时,您只能声明变量(在顶部),但不能直接在主代码块中使用它们。您需要在函数中引用它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2018-02-12
    相关资源
    最近更新 更多