Right now I am having trouble filling an array with spaces. Whenever I use the array fill method I keep getting an exception. Right now I excluded the rest of the code and only included the ones that causes problems. Here it is. Note I am a beginner to java so don't get angry if this is too simple of a question. I have searched here and could not find anything.
public class board
{
public static void main(String args[])
{
char board [][] = new char [6][7];
int column=0;
int row=0;
java.util.Arrays.fill(board,' ');
}
}
The exception says
Exception in thread "main" java.lang.ArrayStoreException:
java.lang.Character
at java.util.Arrays.fill(Arrays.java:2710)
at java.util.Arrays.fill(Arrays.java:2685)
at board.main(board.java:26)
Array.prototype.fill() The fill() method changes all elements in an array to a static value, from a start index (default 0 ) to an end index (default array.length ). It returns the modified array.
fill() method is in java. util. Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array.
An ArrayStoreException is a runtime exception in Java that occurs when an attempt is made to store the incorrect type of object into an array of objects. For example, if an Integer object is attempted to be stored in an String array, a “ java. lang. ArrayStoreException: java. lang.
fill() method is also capable of filling both the 2D and the 3D Arrays. Arrays fill() method has the following syntax: Java. util.
Arrays.fill
expects a single-dimensional array, you're passing in a jagged array.
Instead, do this:
for(int x=0;x<board.length;x++)
for(int y=0;y<board[x].length;y++)
board[x][y] = ' ';
or this:
for(int x=0;x<board.length;x++)
Arrays.fill( board[x], ' ' );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With