Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Arrays.fill() method causes an exception

Tags:

java

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)

like image 709
DrinkJavaCodeJava Avatar asked Sep 24 '12 22:09

DrinkJavaCodeJava


People also ask

What is the use of array fill () method?

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.

What is fill () in Java?

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.

What is array store exception in Java?

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.

Does arrays fill work on 2D arrays?

fill() method is also capable of filling both the 2D and the 3D Arrays. Arrays fill() method has the following syntax: Java. util.


1 Answers

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], ' ' );
like image 145
Dai Avatar answered Oct 21 '22 05:10

Dai