数组不会更新,而是打印出错误的数组

时间:2019-05-16 02:28:27

标签: java

我设法弄清楚如何为连接四程序打印阵列,但是我无法让开发板更新我的代码,我看着它并运行了它,代码在理论上是可行的,但是该阵列不会新输入

我曾经尝试过使用for循环运行它,但结果是错误的,我正在考虑将drop方法放入打印板方法中,但我认为那会导致错误

public class Connect4 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // DON'T MODIFY THE MAIN METHOD UNLESS FOR DEBUGGING

 //MAKE SURE YOU GET RID OF YOUR MODIFICATIONS HERE BEFORE  

SUBMISSION

String[][] board = createEmptyBoard();

Scanner input = new Scanner(System.in);

boolean bl = true;

printPattern(board);

while(bl) {

    int player1 = 1 , player2 = 2 ,  userInput;



 System.out.println("Please drop a RED disk at the column between 0 

and 6:");
    userInput = input.nextInt();
    dropDisk(board, userInput , player1);
    printPattern(board);

   System.out.println("Please drop a YELLOW disk at the column  

between 0 and 6:");
   userInput  = input.nextInt();
   dropDisk(board, userInput , player2);
   printPattern(board);  


    String win = checkWinner(board);
    /*
    Write code to announce  if there is  winner and end the game
    */


} 
 }
 public static String[][] createEmptyBoard() {
   /* This method prints the first empty pattern for the game
   DON'T MODIFY THIS METHOD
   */

    String[][] f = new String[7][15];
    for (int i =0;i<f.length;i++) {
          for (int j =0;j<f[i].length;j++) {

             if (j% 2 == 0) f[i][j] ="|";
             else f[i][j] = " ";
             if (i==6) f[i][j]= "-";
         }
       }
    return f;

} // end of createEmptyBoard 


  public static void printPattern(String[][] brd) {
  for (int i = 0; i < 7; i++){

System.out.println(brd[i][0] + brd[i][1]+ brd[i][2]+ brd[i][3]+ 

brd[i][4]+ brd[i][5]+ brd[i][6]+ brd[i][7]+ brd[i][8]+ brd[i][9]+   

brd[i][10]+ brd[i][11]+ brd[i][12]+ brd[i][13]+ brd[i][14]);

  }

  } // end of printPattern

  public static void dropDisk(String[][] brd, int position, int   

  player) {

       if (player == 1){

            brd[6][position] = "R";

           if(brd[6][position] == "R"){

           brd[6][position]  =  brd[6 - 1][position];

       } 

       }

       else if (player == 2){

           brd[6][position] = "Y";

           if(brd[6][position] == "Y"){

           brd[6][position]  =  brd[6 - 1][position];

       }

       }
/*Write your code to drop the disk at the position the user entered 
   depending on which player*/ 

} // end of dropDisk

2 个答案:

答案 0 :(得分:0)

dropDisk的逻辑似乎尚未完成。 它将brd[6][position]设置为RY,之后立即将其设置为brd[5][position]的当前值。

这应该始终为null

答案 1 :(得分:-2)

在Java中,对象按值传递到方法。这意味着当您将参数传递给函数时,J VM makes a copy of that object which can be modified in the method

在这种情况下,当您将brd传递到dropDisk时,它将被复制,然后您在dropDisk内部对副本进行更改。但是dropDisk结束后,该副本将被丢弃。您的main方法没有对开发板进行任何更改。这是因为您的开发板是一个字符串数组,并且字符串是不可变的,这意味着在实例化之后不能更改它们。

如果您希望从主要方法中更新电路板,请考虑在brd中返回dropDisk