Nathan Matteson
Nathan Matteson

Reputation: 1

How to change one array's values from another array?

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];

Say I was to make sequence[0]="XXO";

How could I take sequence[0] and change the the board points so that:

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

I am trying to run this for loop and I have to initialize the board array before the sequences part as I am printing it out to the screen and can't have the values be null.

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

Upvotes: 0

Views: 170

Answers (3)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

You can use String::split which return an array of String for example :

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

Output

X
X
O

Upvotes: 1

Nadeem
Nadeem

Reputation: 131

As you want only one character as an element in your board array you can use character array instead of String array and then can use

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

Upvotes: 0

Chai T. Rex
Chai T. Rex

Reputation: 3016

You generally shouldn't store the same data in different ways (the Don't Repeat Yourself principle), sometimes because it leads to a mess like this.

One correct way to do what you want is the following:

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

Upvotes: 0

Related Questions