Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java for loop explanation

Tags:

java

for-loop

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"); 
            }
        }
    }                                            
like image 688
user3042022 Avatar asked Feb 16 '26 23:02

user3042022


1 Answers

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.

like image 101
Rahul Avatar answered Feb 19 '26 12:02

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!