首页 > 解决方案 > 定义和使用二维数组的语法错误

问题描述

public class PennyPitch {
  
  int total = 0;
  int[][] board = {{1,1,1,1,1}, {1,2,2,2,1}, {1,2,3,2,1}, {1,2,2,2,1}, {1,1,1,1,1}};
  String[][] boardWithP = {{"1", "1", "1", "1", "1"}, {"1", "2", "2", "2", "1"}, {"1", "2", "3", "2", "1"}, {"1", "2", "2", "2", "1"}, {"1", "1", "1", "1", "1"}};
  
  for(int i = 0; i < 4; i = i + 0){
    int x = (int)(Math.random() * 5);
    int y = (int)(Math.random() * 5);
    
    if(boardWithP[x][y] != "P"){
      total += board[x][y];
      boardWithP[x][y] = "P";
      i++;
    }
  }
}

所以我不断收到语法错误

Syntax error on token ";", { expected after this token

在第 8 行和

Syntax error, insert "}" to complete ClassBody

在线,我想知道是否有人知道问题出在哪里。我所有的括号似乎都匹配,据我所知,第 8 行应该有一个分号。有什么建议么?

标签: javamultidimensional-arraysyntax-error

解决方案


您需要将代码放在方法(函数)中,如下所示:

public class PennyPitch {
  public static void main(String[] args) {
     int total = 0;
     int[][] board = {{1,1,1,1,1}, {1,2,2,2,1}, {1,2,3,2,1}, {1,2,2,2,1}, {1,1,1,1,1}};
     String[][] boardWithP = {{"1", "1", "1", "1", "1"}, {"1", "2", "2", "2", "1"}, {"1", "2", 
      "3", "2", "1"}, {"1", "2", "2", "2", "1"}, {"1", "1", "1", "1", "1"}};
  
    for(int i = 0; i < 4; i = i + 0){
       int x = (int)(Math.random() * 5);
       int y = (int)(Math.random() * 5);
    
       if(boardWithP[x][y] != "P"){
          total += board[x][y];
         boardWithP[x][y] = "P";
         i++;
      }
    }
  } 
}

推荐阅读