如何从另一个数组更改一个数组的值?

时间:2017-06-03 17:21:28

标签: java arrays

String [] board = new String [9];
String [] sequence = new String [8];

sequence[0] = board[0]+board[1]+board[2];
sequence[1] = board[0]+board[3]+board[6];
sequence[2] = board[0]+board[4]+board[8];
sequence[3] = board[1]+board[4]+board[7];
sequence[4] = board[2]+board[5]+board[8];
sequence[5] = board[2]+board[4]+board[6];
sequence[6] = board[3]+board[4]+board[5];
sequence[7] = board[6]+board[7]+board[8];

说我要做sequence[0]="XXO";

我怎样才能取sequence[0]并更改棋盘点,以便:

board[0]="X";
board[1]="X";
board[2]="O";

我正在尝试运行这个for循环,我必须在序列部分之前初始化板数组,因为我将它打印到屏幕并且不能将值设置为null。

for(int i = 0; i < 8; i++
{
    if(sequence[i].equals("X"+"X"+" "))
    {
        sequence[i] = "XXO";
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用String::split返回String数组,例如:

String[] board;//you could also to not initialize the array here 
               //because you will do that in split
String[] sequence = new String[8];
sequence[0] = "XXO";
board = sequence[0].split("");//split and initialize the board array

//print the values
System.out.println(board[0]);
System.out.println(board[1]);
System.out.println(board[2]);

输出

X
X
O

答案 1 :(得分:0)

您通常不应以不同的方式存储相同的数据(the Don't Repeat Yourself principle),有时因为它会导致像这样的混乱。

执行所需操作的一种正确方法如下:

board[0] = String.valueOf(sequence[0].charAt(0));
board[1] = String.valueOf(sequence[0].charAt(1));
board[2] = String.valueOf(sequence[0].charAt(2));

答案 2 :(得分:0)

由于您只需要一个字符作为电路板数组中的元素,您可以使用字符数组而不是字符串数组,然后可以使用

char board[] = new char[9];
board = sequence[0].toCharArray();