Reputation: 325
Specifically if said ArrayList
is made out of String elements, and I'd like to check each letter in those Strings
. This is what I tried, but obviously it doesn't work:
public void fillBoard()
{
board = new char[ROW][COL];
for (String s: words){
for(int rows = 0; rows < board.length; rows++)
{
for(int cols = 0; cols < board[rows].length; cols++)
{
if(!s.equals(board[rows][cols]))
{
board[rows][cols] = randomChar();
}
}
}
}
}
I was trying to compare each char in a 2D
array to the letters in the Strings
that make up the ArrayList
.
The ArrayList
is ArrayList<String> words = new ArrayList<String>();
and it's populated by the users as they enter words when prompted. So it can look like {"hello","goodbye","words",...}
board
is a 2D char array, the dimensions are defined by user input
It's then populated by random chars by this method:
public char randomChar()
{
char alphabet[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z'};
return alphabet[(char)(alphabet.length * Math.random())];
}
}
The intention is that the char board[][]
array may also contain randomly placed words, and when the board is updated, all the letters that aren't part of a string
in the words ArrayList
are randomized again, keeping the words that the user input and where then placed in the array, kind of like updating the board in a battleship program after each turn.
Upvotes: 0
Views: 1707
Reputation: 22452
You are directly comparing the string with a character which needs to be changed and look at the below steps:
(1) Iterate each row of the char
array
(2) Get the string
from list
(3) Now Iterate across the columns of the array and compare with each character in the string
(4) At each step, I have added validations to check if they are comparable in length and break
, if not, you can actually modify this according to your requirement.
You can refer the below code with inline comments:
public static void fillBoard() {
int x=2;//change row size accordingly
int y=2;//change row size accordingly
char[][] board = new char[x][y];
//load the board char array
List<String> words = new ArrayList<>();
//load the list
//Iterate each row of the char array
for(int rows = 0; rows < board.length; rows++) {
//Check if list size is correct to compare
if(rows >= words.size()) {
System.out.println("list size is lower than
the array size,can't caompare these rows");
break;
}
//Get the string from list
String s = words.get(rows);
//Iterate across the columns and compare with string character
for(int cols = 0; cols < board[rows].length; cols++) {
//check if string length is comparable
if(s.length() != board[rows].length) {
System.out.println("list string length is lower
than the array string length,can't caompare ");
break;
}
if(s.charAt(cols) != board[rows][cols]) {
System.out.println(s.charAt(cols)+" is different !!!");
board[rows][cols] = randomChar();
}
}
}
}
Upvotes: 1