user3042022
user3042022

Reputation: 87

Java for loop explanation

I would appreciate some help on this code which I found inside a program but I could not understand it, I have guessed what it does by commenting it, but please correct me if I am wrong.

 for(String[] movieArray:movie)
        {
            for(String data:movieArray)
            {
                if(data!=null){ //If data is not empty then it writes...
                jTextArea1.append(data+", "); //...this to the textarea.
                }
                else{ //If data is empty, then it will stop.
                empty=true;
                break;
                }
            }
            if(empty==false){ //??
            jTextArea1.append("\n"); 
            }
        }
    }                                            

Upvotes: 3

Views: 234

Answers (4)

Prasad
Prasad

Reputation: 1188

 for(String[] movieArray:movie)

This means - loop will continue until there is a value present in movie array. It is equivalent to

for(int i =0; i<movie.length();i++)
    String [] movieArray = movie[i];

WHile 2nd for loop i.e. for(String data:movieArray) means the movieArray that you have created earlier is used here. This loop will continue to execute till there are elements present in movieArray.

Following is the representation of enhanced for loop you've mentioned.

for(int i =0; i<movie.length();i++){
   for(int j = 0; j<movie[0].length(); j++){

Upvotes: 0

Rahul
Rahul

Reputation: 45090

After all the elements in the array movieArray were not null, then they would be appended to jTextArea1 and the empty would stay false(provided it was false initially).

And after the inner for is over, it appends a new line character(\n) if empty was false(this would happen if the condition in the first statement satisfied), else if the empty was set to true(there was a null element in the array), then it would not print the new line character.

Here is how you can better understand it with an example.

movie = {{"1", "2", "3"}, {"4", "5", "6"}}; // Example 1

jTextArea1 would be

1, 2, 3, 
4, 5, 6,

And if

movie = {{"1", null, "3"}, {"4", "5", "6"}}; // Example 2

jTextArea1 would be

1, 4, 5, 6,

That's because in the second case, one of the elements of the array was null and thus it broke out of the for after setting empty as true. And since empty was true, it did not print the new line character.

Upvotes: 1

Premraj
Premraj

Reputation: 7912

Looks like broken for to me ..

 if(empty==false){ //??
  jTextArea1.append("\n"); 
 }

should be inside the for loop

Upvotes: 0

kai
kai

Reputation: 6887

Your comments are right.

/**if no one of the data objects is empty, the boolean `empty` is 
 *still false and then a \n is added to the textarea.
 */
if(empty==false){ 
    jTextArea1.append("\n"); 
} 

empty==false is the same as !empty

Upvotes: 0

Related Questions