转换循环(Java 初学者问题)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5689830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:20:42  来源:igfitidea点击:

Converting loops (Java Beginner question)

javaloopssyntax

提问by Mohammad Fadin

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循环:

 for(xx;yy;zz)
    { 
       aa
    }

While Loop:

虽然循环:

    xx
    while(yy)
    {
      aa
      zz
    }

Do While:

做同时:

      xx
      do
      { 
        aa
        zz
      }
    while(yy)

回答by Tomasz Nurkiewicz

You have couple of mistakes. Especially do-whileloop is incorrect since it always executes at least one iteration, which is not the case for forand whileloops.

你有几个错误。特别是do-while循环是不正确的,因为它总是至少执行一次迭代,而 forforwhile循环并非如此。

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

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

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

回答by gomisha

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

您应该注意for 循环while 循环do-while 循环之间的一些根本区别:

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.

1) 当您知道必须循环多少次时,最好使用 For 循环。例如,当循环一个数字数组时,你需要循环数组中元素的次数。

For loop structure:

For循环结构:

For loop structure

For循环结构

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.

2) 当您不知道必须循环多少次时,最好使用 While 循环。例如,当从文件中读取文本行时,程序会一直读取直到到达文件末尾,而事先不知道它将读取多少行。

While loop structure:

while循环结构:

While loop structure

while循环结构

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.

3) Do-while 循环(又名 do 循环)最适合在您不知道必须循环多少次并且希望至少执行一次循环时使用。例如,如果一个程序不断接受用户的输入并输出它,直到用户输入字母“q”,那么您将使用 do-while 循环,因为您至少需要接受一次用户的输入。

Do-while loop structure:

Do-while 循环结构:

Do-while loop structure

Do-while 循环结构

Source: Loops in Java – Ultimate Guide

来源:Java 中的循环 – 终极指南

回答by Iulius Curt

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

for语句和while语句或do-while语句之间的唯一区别是for还指定了迭代器的初始化和增量。
例如,让我们使用IteratorJava 中的which 可用于迭代向量或类似的东西(例如链表):

//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 whileversion:

这是while版本:

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

The do-whileis very similar to the whileversion.

do-while是非常相似的while版本。

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 foreither.

我确实给了你这个更复杂的例子,向你展示你用 做的while任何事情,无论多么复杂,你都可以用for任何一个。

EDIT: the do-whilestatement 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-whilelike this:

编辑:该do-while语句作为 的替代而存在while,唯一的区别是在迭代的 和 时检查循环条件。因此,您可以使用以下方法制作与上面的示例等效的内容do-while

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.

但这样做没有任何意义。您应该根据自己的目的使用每个工具。

回答by Dilum Ranatunga

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

其他成员已经涵盖了执行语义。但我想添加变量范围语义。

In Java, you can do this:

在 Java 中,您可以这样做:

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.

变量 'i' 被使用了两次。

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

为了将其转换为具有正确范围的 while 循环,您需要使用额外的代码块:

{
  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.

虽然在 Java 中没有那么重要,但在 C++ 等语言中,作用域除了能够使用相同的变量名之外,还有重要的影响。对象销毁、IIA(实例化即获取)等受附加块的影响。

回答by Leon the Logician

// 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()); 
        }
    }
}