javamultidimensional-arraydatafield

In Java: using foreach loops in constructors to initialize multidimensional array data fields


So I'm trying to make a class that encapsulates a 2D array of chars. In particular, what I want to do is define the default constructor so that the encapsulated 2D array contains the default char ('#' in this case). My problem: when I attempt to systematically fill the array with the default char via nested foreach loops, the compiler doesn't acknowledge that I am using the second nested loop's initialized char parameter c, although I obviously am with the assignment c = '#'. To quote Eclipse, "The value of the local variable c is not used."

Here is the relevant code:

public class 2DCharArr
{
 private char[][] chars;
 private byte length_x, length_y;

 public 2DCharArr()
 {
  length_x = 10; length_y = 10;
  chars = new char[length_x][length_y];
  for (char[] arr : chars)
   for (char c : arr)
    c = '#'; // Does not signal to Eclipse that c was used.
 }
}

Is there something wrong with my syntax in the foreach loops, so that the compiler should fail to acknowledge my use of c? It would be great for someone to clear this up for me, since it is keeping me from using foreach loops to create objects that contain multi-dimensional arrays, though I feel like I should be able to if I'm ever to be very competent with the language. Thanks in advance for the insight!


Solution

  • You can't assign values while using an enhanced-for statement. You're going to have to iterate over them the conventional way and assign values into specific indexes.

    for(int i= 0; i < chars.length; i++) {
        for(int j = 0; j < chars[i].length; j++) {
            chars[i][j] = '#';
        }
    }
    

    The reason for this is nuanced in the way that the enhanced for is defined in the JLS:

    In either case, you can't modify the variable being passed in to any meaningful effect, such as assigning values.