How do I access the next element in for each loop in Java?
You either need to use an indexed loop.
for(int i=0;i<strings.length-1;i++) {
String curr = strings[i];
String next = strings[i+1];
}
or you need to compare the current to the previous not the next.
String curr = null;
for(String next: strings) {
if (curr != null) {
// compare
}
curr = next;
}
You can try something like this
String valBefore=new String();
boolean flag=false;
for (String i:str){
if(i.equals("valueBeforeTheExpectedValue")){
valBefore=i;
flag=true;
continue;
} if (flag){
// Now you are getting expected value
// while valBefore has previous value
flag=false;
}
}
You can try like this:
String myArray[]= { "this","is","the","value"};
......
int counter=0;
for(String x:myArray){
counter++;
if(x.equals("value")){
System.out.println(counter);
}
}
This will loop the array, and if the condition is met, the appropriate message will print. In this case it will print 4