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



昨天被问到完全相同的问题时感觉很愚蠢,但今天在不同的情况下可以做同样的事情。

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

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

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

假设split将返回一个代表所需8个元素的Strings数组,则应仅在外循环中执行splits,然后在内循环或数组复制方法中迭代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]);
    }
}

相关内容

  • 没有找到相关文章

最新更新