Can you reset the counter of a for-each Loop? - java

since there's no accessible counter or i in there to reset to zero.
is there any way to play around with continue or break to achieve that?
class CommandLine {
public int[] sort(int array[]) {
int temp;
for (int i=0; i<array.length-1; i++) {//must have used for-each
if (array[i] > array[i+1]){
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
i=-1;
}//if end
}//for end
return array;
}//main end
}//class end

Generally, there is no way of doing this: the iterator that is used to "drive" the for-each loop is hidden, so your code has no access to it.
Of course you could create a collection-like class that keeps references to all iterators that it creates, and lets you do a reset "on the side". However, this qualifies as a hack, and should be avoided.
If you need a way to reset the position of your iteration back to a specific location, use a regular for loop.

No, the for each loop internally does not use any counter. Therefore, just use an usual loop like:
for (int i = 0; i < myCollection.size(); i ++) {
// do something
}
More information: Is there a way to access an iteration-counter in Java's for-each loop?

Related

Why are variable not recognised from inside for-statements?

What I am trying to do is create an array that pulls even numbers from another array. I'm not sure if I have gone about it the right way. I've look for ways of returning from statements like you would functions/methods and I can't find anything, not even sure if it is possible.
Anyway, the issue I am having here is the 'return evenArray' below 'cannot find symbol.' I am not sure what this means?
public static int[] getEvenArray(int[] array)
{
int dividedBy = 2;
int evenElement;
int evenCount = 0;
for(int i = 0; i < array.length; i++)
{
int[] evenArray;
evenElement = array[i] % dividedBy;
if(evenElement == 0)
{
evenCount++;
}
else
{
array[i] = 0;
}
evenArray = new int[evenCount];
for(int x = 0; x < evenArray.length; x++)
{
if(array[i] != 0)
{
evenArray[x] = array[i];
}
}
}
return evenArray;
}
This is for a tutorial from one of my lectures, it's a little bit challenging to say the least :-)0
evenArray is defined within the scope of the for loop. (Actually a little worse than that; you're redeclaring it on each iteration so discarding the previous contents).
So once you're outside the for loop you can't refer to it.
Quickest fix is to use a std::vector<int> for this type, and declare it at the start of the function. Also change the return type of the function to the same. Don't forget to size the vector appropriately.
(Moving on, a smart lecturer will ask you about returning a std::vector which could potentially take a deep copy of that vector. Pre C++11 you'd mention return value optimisation, now you can talk about r-value references. No deep copy will be taken since the move constructor will be used).
Variable declared inside a block is not visible outside of it; move this int[] evenArray; to very start of function.

Is it more efficient to declare a variable inside a loop, or just to reassign it?

While writing loops I often get confused with which one I should choose. For example,
int sum;
for(int i=0; i<10; i++)
{
sum=0;
...
....
}
Or
for(int i=0; i<10; i++)
{
int sum=0;
...
....
}
Say, the variable is only required in this loop. There is no need of it in the later part of the program. I need the value of the variable sum to be 0 at the beginning of the loop.
Which one is the better practice? Re-initializing a variable at the start of the loop or re-declaring it? Which one is more efficient?
If you declare a variable outside of the loop and not use it past the loop, the compiler will move the declaration inside the loop.
That means there is no reason to compare efficiency here, since you end up with the same exact code that the JVM will run for the two approaches.
So the following code:
int sum;
for(int i=0; i<10; i++)
{
sum=0;
}
... becomes this after compilation:
for(int i = 0; i < 10; i++)
{
int sum = 0;
}
This leads us to concentrate on performance and optimization of code in looping concepts.
From a maintenance perspective, second case is better. Declare and initialize variables in the same place, in the narrowest scope possible. Don't leave a gaping hole between the declaration and the initialization.The scope of local variables should always be the smallest possible.See the link
Declaring variables inside or outside of a loop
Re initializing it within the loop will set the sum value to zero every time you start the loop, no need to re-declare. The answer is both have same efficiency.

Loop to check a variable

I want to loop through an array, then I want to do a check to see if the element in the arrayList is bigger than a certain number.
for(int i = 0; i < NewUser.getList().size(); i++){
if(UserAge < 50){
System.print.out.ln(UserAge)
}
}
but Im not sure on this, because i don't know how to use every element of the arrayList as part of the if, not UserAge
If it's an ArrayList you can simply iterate it without using counts etc:
for( int i : myList ){
if( i > 50 ){
}
}
To put it bluntly, you're not retrieving the elements from your list. You're comparing against a static value which will never change throughout the loop.
(You've also got some fun syntax issues, but I'll overlook those for now...)
To retrieve the elements, you have two options:
Use the i variable:
for(int i = 0; i < NewUser.getList().size(); i++){
Integer userAge = NewUser.getList().get(i);
if(userAge < 50){
System.out.println(userAge);
}
}
Use the enhanced-for statement, giving you a variable for free:
for(Integer userAge : NewUser.getList()){
if(userAge < 50){
System.out.println(userAge);
}
}
Enhanced for is recommended for collections, as it reads a lot clearer. Only index into collections and arrays if you need to get something at an exact position.

java arraylist iteration

Is this going to cause unpredictable behavior?
ArrayList<X> x = new ArrayList<>();
//x.add(new X())...
f:
for(int i = 0; i < x.size() -1;)
{
X y = x.get(i);
for(int j = i + 1; j < x.size();)
{
if(a) {
x.remove(j);
continue;
}
if(b) {
x.remove(i);
continue f;
}
j++;
}
i++;
}
I don't think it will be unpredictable, but your style seems wrong to me, so your approach is suspect.
Using a label is a bad idea, and deciding to use it shows that your approach is flawed.
You may want to look at this discussion about deleting on ArrayList, but basically, LinkedList would be fsster:
http://www.velocityreviews.com/forums/t587893-best-way-to-loop-through-arraylist-and-remove-elements-on-the-way.html
But, removing this way will work.
UPDATE:
Oops, just saw a couple of bugs:
if(a) {
x.remove(j);
continue;
}
OK, in this one, you will go back through the loop for j, but you didn't increment j.
if(b) {
x.remove(i);
continue f;
}
This is the same for i.
So, you need a similar change to fix it:
for(int i = 0; i < x.size() -1; i++)
This way, when you hit continue then it will still go to the next element.
It would be better to create an array which contains indexes to remove.
And fill it with indexes in the main for cycle. Than you can do something like this:
Collections.sort(indexesToRemoveArr);
Collections.reverse(indexesToRemoveArr);
for (int indexToRemove : indexesToRemoveArr) {
arr.remove((int) indexToRemove );
}
In that code I remove indexes from end to start. That's why it won't do any problems.
Yes. Compiler will optimize and call x.size() only once. So your terminatin condition becomes incorrect as soon as you remove element.

Break in nested for loops [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to Break from main/outer loop in a double/nested loop?
I have the following situation:
for(int i = 0; i < schiffe.length-1; i++){
if(schiffe[i].schaden){
schlepper.fliege(schiffe[i].x,
schiffe[i].y,
schiffe[i].z);
schlepper.wirdAbgeschleppt = schiffe[i];
for(int k = 0; k < stationen.length-1; k++){
if(stationen[k].reparatur == null){
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
break;
}
}
}
}
I want to
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
be performed once and then break out of the inner loop and continue with the for(int i... loop. So I used a break in my code. But I am not really sure if this is right. Does the break cause a break for all loops or just for the second loop?
It breaks only the inner loop, and therefore does what you want. To break more than one level, in Java, you can use a "labelled break" like so:
schiffe_loop:
for(int i = 0; i < schiffe.length-1; i++){
some_stuff();
for(int k = 0; k < stationen.length-1; k++){
if (something_really_bad_happened()) {
break schiffe_loop;
}
}
}
But usually you will not need this.
You may consider making a separate method for the inner loop anyway; it's something you can easily give a name to ("find_available_station" or something like that), and will probably need somewhere else.
Also, please be aware that your loops right now will miss the last element of each array. Think carefully about why you are using < instead of <=; it's exactly so that you use every value from 0 up to but not including the specified one.
break will break the innermost loop, in your case 2nd loop.
To make it break the outer loop you can use a labeled break as:
OUTER:for(...) {
for(...) {
break OUTER;
}
}
break only breaks out of the innermost loop.
break will cause break for closest loop only (second loop)
Just the second one. You can use "goto" of course.
Break statement terminates the closest enclosing loop or switch statement in which it appears in many languages but you can try it and be sure 100%.
put the inner two loops in a function and use return to break out of both of them.
If you need more control, you can use a labeled break. More info here. As others have said, break will close the closest loop.
What about using a boolean you call 'found' and use it like this:
while(!found) {
for(...) {
//todo
}
}
I Think You Can Do One More Thing..
for(int k = 0; k < stationen.length-1; k++){
if(stationen[k].reparatur == null){
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
k = stationen.length + 1 ;
}
}

Categories