I posted a reply a few days ago, and I must have been tired as I missed a break
statement. However the behavior of the code puzzled me:
String desc = "Key1: Val1 ; Key2: Val2 ; Key3: Val3 ; Key4: Val4 ; Key5: Val5";
String[] parts = desc.split(";");
System.out.println("For Each -------------------------");
for ( String part : parts )
{
System.out.println(part);
if ( part.contains("Key3") )
{
parts = part.split(":");
System.out.println("***************** Value is: '" + parts[1].trim() + "'");
}
}
System.out.println("For Each -------------------------");
Produces
For Each -------------------------
Key1: Val1
Key2: Val2
Key3: Val3
***************** Value is: 'Val3'
Key4: Val4
Key5: Val5
For Each -------------------------
The strange part is that I changed the contents of parts
midway through the foreach
loop. This should have caused an error, as the value and length of parts
changes.
The loop using an index
String desc = "Key1: Val1 ; Key2: Val2 ; Key3: Val3 ; Key4: Val4 ; Key5: Val5";
String[] parts = desc.split(";");
System.out.println("Index -------------------------");
for ( int i = 0; i < parts.length; i++ )
{
System.out.println(parts[i]);
if ( parts[i].contains("Key3") )
{
parts = parts[i].split(":");
System.out.println("***************** Value is: '" + parts[1].trim() + "'");
}
}
System.out.println("Index -------------------------");
Produces
Index -------------------------
Key1: Val1
Key2: Val2
Key3: Val3
***************** Value is: 'Val3'
Index -------------------------
The loop ends because the length of parts
is changed, and the for test
exits the loop. We never see Key4 and Key5.
The question is, why does the foreach
loop continue, and with what values?
This was run using Eclipse and a jpage file.