(2D数组)Java错误:需要常量表达式

时间:2019-02-11 09:15:22

标签: java data-structures

我正在为数据结构做作业,而在使用2D数组时遇到了麻烦。这是我要做的:

”“假设您正在设计一个n≥1000的多人游戏, 从1到n的数字,在魔法森林中互动。这个的赢家 游戏是第一个至少可以与所有其他玩家会面的玩家 一次(允许领带)。假设有一个方法met(i,j), 每当玩家i遇到玩家j(i̸= j)时都会被调用, 描述一种跟踪会议参与者对和谁是赢家的方法。”

由于此错误,我无法编译:

  

Multiplayer.java:51:错误:需要常量表达式

此行:

case meet: sb.append("1");

我是一个初学者,因此我非常感谢您的帮助。预先谢谢你!

/* Suppose you are designing a multiplayer game that has n≥1000
   players, numbered 1 to n, interacting in an enchanted forest. The winner
   of this game is the first player who can meet all the other players at 
   least once (ties are allowed). Assuming that there is a method meet(i,
   j), which is called each time a player i meets a player j (with i ̸=
   j), describe a way to keep track of the pairs of meeting players and 
   who is the winner. */

public class Multiplayer {
    int n; // number of players
    int map[][] = new int[n][n]; // create a 2D array
    int meet = 1;
    int notMeet = 0;
    int[] count; // an array to keep the count, player wins when it reaches n

    public Multiplayer() {
        clearMap();
    } // initiate a new game

    public void clearMap() { // clear the 2d array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                map[i][j] = notMeet; // clearing the map
                count[i] = 0; // turn every value of count[] into 0
                if (i == j)
                    map[i][j] = map[j][i] = meet; // when i == j give the tile the value of 1
            }
        }
    }

    public void meet(int i, int j) {
        // when player i meets player j, add 1 to the count[] of each player
        count[i] = count[i] + 1;
        count[j] = count[j] + 1;
    }

    public int isWin() {
        for (int i = 0; i < n; i++) {
            if (count[i] == n)
                return i; // player at the index i wins
        }
        return -1; // no player won yet
    }

    public String toString() {
        // display the map in string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                switch (map[i][j]) {
                case meet:
                    sb.append("1"); // if player i and j meets, put 1 in the map //this line causes error
                default:
                    sb.append("0"); // if they haven't met, put the 0 as default
                }
                if (j < n - 1)
                    sb.append("|");
            }
            if (i < n - 1)
                sb.append("\n-----\n");
        }
        return sb.toString();
    }
}

class MultiplayerTest {
    public static void main(String[] args) {
        Multiplayer newGame = new Multiplayer();
        newGame.n = 5; // test for a small number of players
        // test for player 1 to meet all other players
        for (int i = 2; i <= 5; i++) {
            newGame.meet(1, i);
        }
        // print test to see if player 1 wins the game
        System.out.println(newGame.toString());
        System.out.println(newGame.isWin());

    }
}

6 个答案:

答案 0 :(得分:0)

您不能在switch语句中使用变量作为标签。

如果您希望程序中具有恒定值,通常的方法是创建一个静态最终成员:

public static final int MEET = 1;

但是,在这种情况下,如果只有两个值,则最好使用布尔数组,并且只检查true和false。不需要switch语句。

boolean map[][] = new boolean[n][n];

...

if (map[i][j]) {
    ...

在这种情况下,最好重命名满足的数组,因此您的代码应如下所示:

if (met[i][j]) {
    ...

答案 1 :(得分:0)

在以下代码段中:

switch (map[i][j]) {
    case meet:
        sb.append("1"); // if player i and j meets, put 1 in the map //this line causes error
    default:
        sb.append("0"); // if they haven't met, put the 0 as default
}

请注意,由于没有break;语句,因此根据fall through逻辑,它将始终附加0

如果只有一个case,则应该使用if,例如:

if(map[i][j] == meet) {
    sb.append("1");
}else {
    sb.append("0");
}

更新

关于NullPointerException,您将收到该异常,因为count数组未初始化,并且您正在尝试访问该元素。

将声明更改为以下内容:

int[] count = new int[n];

答案 2 :(得分:0)

您需要初始化count数组,例如

public void initializeArray(int n) {
    this.n = n;
    count = new int[n];
    for (int i = 0; i < n; i++) count[i] = 0;
}

然后代替

newGame.n = 5;

您需要这样做:

initializeArray(5);

答案 3 :(得分:0)

我看不到您实际在哪里创建数组计数。 您的代码:     boolean met [] [] =新的boolean [n] [n]; //编辑     int [] count; //保留计数的数组,玩家到达n时获胜 创建满足的数组(... = new boolean [n] [n]),但没有用于数组计数的语句。因此,对count [i]的引用失败。

答案 4 :(得分:0)

所以我像你们建议的那样固定了代码。非常感谢大家!下面的这段代码仍然有一个错误,但是比我的原始代码要好得多。有人知道ArraysIndexOutOfBound错误吗?

import java.util.Arrays;
public class Multiplayer {


    int n; //number of players
    boolean met[][] = new boolean [n][n];
    int[] count; //an array to keep the count, player wins when it reaches n

    public Multiplayer() {clearMap(); } //initiate a new game

    public void clearMap() {
        for (int i = 0; i < n; i ++) {
            for (int j = 0; j < n; j++) {
                met [i][j] = false; //clearing the map
                count [i] = 0;  //turn every value of count[] into 0
                if (i == j)
                    met[i][j] = met[j][i] = true;
            }
        }
    }

    public int[] meet(int i, int j){
        //when player i meets player j, add 1 to the count[] of each player
        if (i != j) {
            count [i] = count[i] + 1; 
            count [j] = count [j] + 1;
            met [i][j] = met[j][i] = true;

        }
        //System.out.println(Arrays.toString(count));
        return count;
    }

    public void initializeArray(int n) {
        this.n = n;
        count = new int[n];
        for (int i = 0; i < n; i++) count[i] = 0;
    }

    public int isWin () {
        for (int i = 0; i < n ; i++){
            if (count[i] == n-1) //if player i meets all the other players 
                return i; //player at the index i wins
        }
        System.out.println(Arrays.toString(count));
        return -1;
    }

    public String toString() {
        //display the map
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <n; j++) {
                if (met [i][j]) {sb.append("true");} //this line causes error ArrayIndexOutofBound
                else {sb.append("false");}
                if (j<n-1) sb.append ("|");
            }
            if (i<n-1) sb.append("\n-----\n");
        }
        return sb.toString();   
    }
}


class MultiplayerTest {
    public static void main (String[] args) {
        Multiplayer newGame = new Multiplayer ();
        newGame.initializeArray(5); //test for a small number of players
        //test for player 1 to meet all other players
        for (int k = 0; k < 5; k++) {newGame.meet (1,k); }
        //print test to see if player 1 wins the game
        System.out.println(newGame.isWin());
        //System.out.println(newGame.toString()); I tried printing the 2D array output into String but encountered an error and don't know how to fix it, but the other methods are fine.

    }
}

答案 5 :(得分:0)

“需要常量表达式”表明在切换情况下的标签需要一个常量。正如其他答案所建议的那样,最好使用if和布尔2d数组。
ArraysIndexOutOfBound错误实际上是由于您需要在构造函数方法中使用new运算符创建数组,然后将引用传递给 映射为map = new boolean[n][n];

我在这里尝试过

public class Multiplayer {
  int n; //number of players
  boolean[][] map; //not initializing here but in constructor
  int[] count; //an array to keep the count, player wins when it reaches n

  public Multiplayer(int num){
    n=num;
    map = new boolean[n][n];
    count = new int[n];
    //No need to use clearMap as all instance variables are assigned the default value of 0 or false or null;
    for(int i=0;i<n;i++){ //self-meeting
      count[i]=1;
      map[i][i]=true; 
    }
  }

  public void meet(int i,int j){
    if(i==j) return;
    //player number 1 is at index number 0
    //Hence player i is at index number i-1
    i--;j--;
    count[i]+=1;
    count[j]+=1;
    map[i][j]=map[j][i]=true;
  }

  public int isWin(){
    for(int i =0;i<n;i++)
      if(count[i]==n)
          return i; // player at the index i wins
    return -1; // no player won yet
  }

  public String toString(){
    String s = "";
    for(int i=0;i<n;i++){
      for(int j=0;j<n;j++){
        if(map[i][j])  s+="1";
        else           s+="0";
        if(j<n-1)      s+="|";
      }
      s+="\n";
      for(int k=0;k<n && i<n-1;k++)
        s+="--";
      s+="\n";
    }
    return s;
  }
}

public class MultiplayerTest {
  public static void main(String[] args) {
    int numberOfPlayers = 5;
    Multiplayer newGame = new Multiplayer(numberOfPlayers);
    // test for player 1 to meet all other players
    for (int i = 2; i <=5; i++) {
      newGame.meet(1, i);
    }
    // print test to see if player 1 wins the game
    System.out.println(newGame.toString());
    System.out.println(newGame.isWin());
  }
}
相关问题