错误:与2D数组和.split不兼容的类型

时间:2015-06-30 00:00:37

标签: java multidimensional-array incomplete-type

感觉愚蠢的问题就像昨天完全相同的问题,但今天有不同的情况可以做同样的事情。

single[z][i] = (board[i].split("?!^"));  

这一行给出了一个错误:需要不兼容的类型:String 发现:String [] 1错误 我知道它,因为它的2D数组和分割给它自己的字符串输出,但不知道如何修复。 这是我的所有代码:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int player;
    String board[] = new String[8];
    String single [] [] = new String [8] [8];

    //single[0][0] = "hi";

    //If player is 1, I'm the first player.
    //If player is 2, I'm the second player.
    player = in.nextInt();

    //Read the board now. The board is a 8x8 array filled with 1 or 0.

      for(int i = 0; i < 8; i++) {
          if(in.hasNext()){
              board[i]= in.next();

         }
      }
  for(int z = 0; z < 8; z++){
       for(int i = 0; i < 8; i++) {
           single[z][i] = (board[i].split("?!^"));   

    }
  }for(int z = 0; z < 7; z++)
       for(int i = 0; i < 7; i++) {
           if((single[z][i].equals(1)) && (single[z][i+1].equals(1)) &&(single[z+1][i].equals(1))){
               System.out.print(z + ""+ i);
           }
       }


    nextMove(player,board);

   }

   }

1 个答案:

答案 0 :(得分:0)

假设split期望返回表示所需8个元素的String s数组,则应仅在外部循环中执行split s,然后迭代内循环或数组复制方法中split的结果:

for(int z = 0; z < 8; z++){
    String[] tokens = board[z].split("?!^");
    // Should have at least 8 tokens here.
    // Copy the first 8 into single[z]
    single[z] = new String[8];
    System.arraycopy(tokens, 0, single[z], 0, 8);
}

如果你知道每个split只返回8个项目,你可以用更简单的方式做到:

for(int z = 0; z < 8; z++){
    single[z] = board[z].split("?!^");
}
for(int z = 0; z < 8; z++){
    for(int i = 0 ; i < 8 ; i++) {
        System.out.print("single["+z+"]["+i+"]=");
        System.out.print(single[z][i]);
    }
}