首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用'for loop‘代替'while loop’

如何使用'for loop‘代替'while loop’
EN

Stack Overflow用户
提问于 2010-07-11 06:51:47
回答 4查看 322关注 0票数 0

我不得不使用while、do-while和for循环为一个在线的pre java类编写以下程序。寻找一个小小的解释。提前感谢!

PS在寻找参考书时,这是Java还是Javascript?对于一本好的参考书有什么建议吗?我理解了这个概念,大部分情况下,魔鬼当然是在细节中。

代码语言:javascript
复制
public class ExamsFor {

    public static void main(String[] arguments) {


    int inputNumber; // One of the exams input by the user.
    int sum;     // The sum of the exams.
    int count;   // Number of exams.
    Double Avg;    // The average of the exams.


    /* Initialize the summation and counting variables. */

    sum = 0;
    count = 0;

    /* Read and process the user's input. */

    TextIO.put("Please enter the first exam: "); // get the first exam.


        inputNumber = TextIO.getlnInt();

    for (inputNumber!=0; sum += inputNubmer; count++ ) {  // had the while loop below enter here, worked

    TextIO.put("Please enter the next exam, or 0 to end: "); // get the next exam.  
    inputNumber = TextIO.getlnInt();
    } 

    /* Display the result. */

    if (count == 0) {
    TextIO.putln("You didn't enter any data!");
    }
    else {
    Avg = ((double)sum) / count;
    TextIO.putln();
    TextIO.putln("You entered " + count + " exams.");
    TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
    } 

    } // end main ()
}  // end class ExamsFor

/*  Had the following 'while loop' in place of the 'for loop'


while (inputNumber != 0) {
    sum += inputNumber;  // Add inputNumber to running sum.
    count ++;        // Count the input by adding 1 to the count.

*/
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-07-11 08:07:23

您的for循环不应该是:(请注意前面的内容;以及sum+=inputNumber中的拼写错误)

代码语言:javascript
复制
for (;inputNumber!=0; sum += inputNumber, count++ )

while循环应该是

代码语言:javascript
复制
while(inputNumber!=0) {
// rest of the things
 sum+=inputNumber;
 count++;
}
票数 1
EN

Stack Overflow用户

发布于 2010-07-11 07:10:08

您可以比较forwhile语句,观察到您在迭代构造中主要需要4件事:

condition (A)

  • a条件中使用的值的初始值,用于检查是否保持迭代(B)

  • a语句,该语句修改每次(C)

  • the语句本身的正文时检查的值(BODY)

对于for,您有

代码语言:javascript
复制
for (A; B; C)
  BODY

而对于while (这里充满了文字笑话:),您的代码如下

代码语言:javascript
复制
A;
while (B)
{
  BODY;
  C;
}

这很简单,不是吗?

票数 5
EN

Stack Overflow用户

发布于 2010-07-11 07:02:10

阅读this并将您的for循环与预期的语法进行比较,看看哪里出了问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3221132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档