2

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!

4

2 に答える 2

4

拡張 for ステートメントの使用中に値を割り当てることはできません。それらを従来の方法で繰り返し処理し、値を特定のインデックスに割り当てる必要があります。

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

この理由は、強化された forが JLS で定義されている方法に微妙な違いがあります。

  • の場合は、変数にバインドされIterableた結果でイテレータを使用します。next()
  • 配列型の場合は、インデックス値が変数にバインドされた for ループが作成されます。

いずれの場合も、渡される変数を変更して、値の割り当てなどの意味のある効果を得ることはできません。

于 2014-10-01T00:57:32.627 に答える
1

割り当ての使用を混乱させています:

int x = 5;
int y = x;
y = 6;

x の値を変更しません。あなたの内側のループは本質的に「言っている」:

char c = arr[current index];
c = '#';

これは の値を変更せず、arr[current index]単に の値cを '#' に変更しますが、元のarr配列は変更しません。cコンパイラは、作成している変数が使用されていない (つまり、読み取られていない) ことを警告しています。

このループは問題なく機能することに注意してください。

for (char[] arr : chars)
    for (int x = 0; x < arr.length; x++)
        arr[x] = '#';

外側の foreach ループは、内の現在のオブジェクトarrを指すように変数を割り当てます。次に、x 番目の要素に値 '#' を割り当てます。char[]charsarr[x]

于 2014-10-01T01:11:37.430 に答える