开发者

Converting loops (Java Beginner question)

开发者 https://www.devze.com 2023-02-25 20:39 出处:网络
Does Converting between loops always works like this? or there is some situation that it does not? and what is the fastest way to check while I\'m solving a question like this in Exam?

Does Converting between loops always works like this? or there is some situation that it does not? and what is the fastest way to check while I'm solving a question like this in Exam?

For Loop:

 for(xx;yy;zz)
    { 
       aa
    }

While Loop:

    xx
    while(yy)
    {
      aa
      zz
    }

Do While:

      xx
      do
      { 
        aa
       开发者_C百科 zz
      }
    while(yy)


You have couple of mistakes. Especially do-while loop is incorrect since it always executes at least one iteration, which is not the case for for and while loops.

for(x(); y(); z())
{ 
   a();
}

x();
while(y())
{
  a();
  z();
}

x();
if(y())
{
  do
  { 
    a();
    z();
  } while(y())
}


There are some fundamental differences between a for loop, while loop and do-while loop that you should be aware of:

1) For loops are best used when you know how many times you have to loop over something. For example, when looping over an array of numbers you will need to loop over as many times as there are elements in the array.

For loop structure:

Converting loops (Java Beginner question)

2) While loops are best used when you don’t know how many times you have to loop over something. For example, when reading lines of text from a file, a program will keep reading until it gets to the end of the file, without knowing beforehand how many lines it will read.

While loop structure:

Converting loops (Java Beginner question)

3) Do-while loops (aka do loops) are best used when you don’t know how many times you have to loop over something AND you want to execute the loop at least once. For example, if a program continuously takes input from the user and outputs it, until the user enters the letter “q”, then you would use a do-while loop since you would need to take the user’s input at least once.

Do-while loop structure:

Converting loops (Java Beginner question)

Source: Loops in Java – Ultimate Guide


The other members have covered the execution semantics. But I wanted to add the variable scoping semantics.

In Java, you can do this:

for (Iterator<String> i = localList.iterator(); i.hasNext(); ) {
  String element = i.next();
  if (...) {
    i.remove();
  }
}

for (Iterator<String> i = importList.iterator(); i.hasNext(); ) {
  String element = i.next();
  if (...) {
    i.remove();
  }
}

Where the variable 'i' is used twice.

In order to translate that to while loops with correct scoping, you need to use additional code blocks:

{
  Iterator<String> i = localList.iterator();
  while (i.hasNext()) {
    String element = i.next();
    if (...) {
      i.remove();
    }
  }
}

{
  Iterator<String> i = importList.iterator();
  while (i.hasNext()) {
    String element = i.next();
    if (...) {
      i.remove();
    }
  }
}

Note how the additional { ... } allows you to use the same variable names.

While not as important in Java, in languages like C++, the scoping has important ramifications beyond just being able to use the same variable names. Object destruction, IIA (instantiation is acquisition) etc are affected by the additional block.


The only difference between a for statement and a while statement, or a do-while statement is that the for also specifies the initialization and the incrementation of the iterator.
For example, lets take an Iterator which in Java can be used to iterate through a vector or something similar (linked list for example):

//we already have a variable v whom type implements List interface;
for (Iterator vectorIterator = v.iterator(); vectorIterator.hasNext(); ) {
    //I left blank after the last ";" because there should come
    // the increment statement, and I need to store the .next() return value.

    int current = vectorIterator.next();
}

And here is the while version:

Iterator vectorIterator = v.iterator();
while (vectorIterator.hasNext()) {
    int current = vectorIterator.next();
}

The do-while is very similar to the while version.

I did give you this more complex example to show you that anything you do with while, no matter how complex, you can do with for either.

EDIT: the do-while statement exists as an alternative to while, with the only difference that the looping condition is checked at the and of an iteration. So you can make an equivalent to the example above using do-while like this:

Iterator vectorIterator = v.iterator();
if (vectorIterator.hasNext()) {
    do {
        int current = vectorIterator.next();
    } while (vectorIterator.hasNext());
}

but there is no purpose in doing that. You should use each tool for it's own purpose.


// This class demonstrates the transliteration
// between while, for, and for-each loop syntax
public class LoopTest {

    // This method definition showcases do-while-loop syntax 
    public void doWhileLoop(Person[] people) {
        int i=0;
        do {
            Person p = people[i];
            System.out.println(p.getName());
            i++;
        }while(i<people.length);
    }

    // This method definition showcases while-loop syntax 
    public void whileLoop(Person[] people) {
        int i=0;
        while(i<people.length) {
            Person p = people[i];            
            System.out.println(p.getName());            
            i++;
        }
    }

    // This method definition showcases for-loop syntax    
    public void forLoop(Person[] people) {
        for(int i=0; i<people.length; i++) {
            Person p = people[i];            
            System.out.println(p.getName());             
        }
    }

    // This method definition showcases for-each-loop syntax        
    public void forEachLoop(Person[] people) {
        for(Person p : people) {
            System.out.println(p.getName()); 
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号