Converting loops (Java Beginner question)

前端 未结 5 410
独厮守ぢ
独厮守ぢ 2020-12-20 06:45

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 th

相关标签:
5条回答
  • 2020-12-20 07:12

    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.

    0 讨论(0)
  • 2020-12-20 07:14

    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.

    0 讨论(0)
  • 2020-12-20 07:20

    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())
    }
    
    0 讨论(0)
  • 2020-12-20 07:25

    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:

    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:

    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:

    Source: Loops in Java – Ultimate Guide

    0 讨论(0)
  • 2020-12-20 07:26
    // 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 讨论(0)
提交回复
热议问题