Re: Emptying an array of string
From: Tony Morris (not_at_telling.you)
Date: Sat, 05 Jun 2004 05:32:43 GMT
"Huub" <email@example.com> wrote in message
> I have filled a 2-dimensional array of string and want to empty all
> elements and fill the array again. I try to do this:
> for (int i = 0; i < 3; i++)
> for (int j = 0; j < 3; j++)
> vak[i][j] = "";
> but it keeps telling me each element already is occupied. What am I
> doing wrong?
> BTW, no error message is being given, just the output to screen I built
> in that says that the element already is occupied.
When I run that piece of code, I see nothing but compile error messages, not
"the element already is occupied".
Perhaps you might consider rewriting that code since you seem to have the
common misconception that Java allows multi-dimensional arrays. Java
permits arrays of arbitrary type, which may be yet another array (I assume
this is what you have). This is not the same as a multi-dimensional array
(as in COBOL for example).
So, to rewrite your code correctly:
String vak = new String; // Declares a String array of arrays
// iterate the array
for(int i = 0; i < vak.length; i++)
// Get one of the elements of the array, which happens to also be an
String element = vak[i];
// Iterate the array that is an element of an array
for(int j = 0; j < element.length; j++)
// Get one of the elements of the array
String s = element[j];
To reiterate, Java does not allow you to declare multi-dimensional arrays.
To some (especially those who have never used a language with true
multi-dimensional arrays), this statement might seem pedantic and academic,
but I'll speculate that your problems (and some other problems that are
encountered by newcomers to the language) are a direct consequence of
believing this fallacy.
-- Tony Morris (BInfTech, Cert 3 I.T., SCJP[1.4], SCJD) Software Engineer IBM Australia - Tivoli Security Software (2003 VTR1000F)