PDA

View Full Version : Java Question (Off topic but technical)


myxomatosii
08-21-2015, 03:27 PM
Hey guys, I've done various programming. Mostly scripting but now I'm getting into Java and want to become legit at it so I'm not skimming over shit I get lost at but this one is really perplexing me. So I'm taking this online course and the code below was shown to me, along with the description in the tags and I think I get what its doing but wanted to ask.

Where the heck did "for (int element:array)" come from? How was I supposed to know what that meant and that you could do that? I was confused because as far as I could see "element" never got defined and searching Google didn't turn it up as a keyword or reserved word within Java so.. what the hell is it?

I take that its just incrementing across each element and storing the highest values to value and the lowest values to value2, basic stuff but the "for (int element:array)" statement, is that just something I need to accept or is there some ruleset it follows?:confused:


I should note I'm confused because up until this point FOR loops mostly took the regular syntax "for (int x=0;x<100;x++)" or whatever.

public static void main(String[] args) {
int array[] = {81,13,10,34,23,234,8,33};
int value = array[0];
int value2 = value;
for (int element : array){
if (element > value){
value = element;
}
if (element < value2){
value2 = element;
}
}
System.out.println(value+" "+value2);

}

/**
This code stores in value the maximum value of the array and
in value2 the minimum value of the array.

At the beginning of the code, both value and value2 are set
to the first element of the array, that is,
value=value2= array[0] = 81

Within the loop, the variable element is set in each iteration
to a value of the array. So, the first iteration element=81,
the second element=13, the third element=10, and so on.

The number of iterations is equal to the number of elements
on the array, that is, 8.

Each iteration element is first compared with value, and if
element is greater than value, the code makes value = element.
As the loop goes through all the elements in the array, at
the end of the code, value = 234, that is the maximum value
within the array.

The same happens with value2, but it will store the minimum
value of the array, that is, value2 = 8
*/