定义和使用2d数组时出现语法错误

xyhw6mcr  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(403)

**结案。**此问题不可复制或由打字错误引起。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

27天前关门了。
改进这个问题

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行应该有一个分号。有什么建议吗?

66bbxpm5

66bbxpm51#

问题不在于多维数组,多维数组很好。问题是您不能直接在 class -它需要在方法、构造函数或初始值设定项块中。例如。:

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"}};

  public static void main(String[] args) { // Here!
    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++;
      }
    }
  }
}

另外,作为旁注,您不应该使用 == 或者 != 运算符比较字符串,但使用 equals 方法。查看如何比较java中的字符串?详情。

pvcm50d1

pvcm50d12#

您需要将代码放入如下方法(函数)中:

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++;
      }
    }
  } 
}

相关问题