我如何将这个for循环转换为while循环? [英] How do I convert this for loop into a while loop?

查看:130
本文介绍了我如何将这个for循环转换为while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个数组程序。我正在练习如何将循环转换为循环,但是我无法理解这个概念。



如果我有 for 循环:

  int [] list = new int [5]; 

for(int i = 0; i <5; i ++){
list [i] = i + 2;

$ / code>

我如何使它成为循环?

这是我的尝试
$ b $ pre $ int [ ] list = new int [5];
int i = 0;

while(i <5){
list [i] = i + 2;
i ++;
}
System.out.print(list [i] +);

这是我认为应该完成的事情,但在我的电脑中出现错误。 / p>


线程main中的异常java.lang.ArrayIndexOutOfBoundsException:5在Arrays2.main(Arrays2.java:21)


这是行21

  System.out。 print(list [i] +); 


解决方案

一个基本的for语句的一般结构是:< (ForInit; Expression; ForUpdate)语句



  


  • ForInit 是初始值设定项。它是首先设置变量等。

  • 表达式是一个布尔条件来检查是否 Statement 应该运行

  • 语句是要运行的代码块,如果 Expression 为true

  • ForUpdate Statement 例如根据需要更新变量



ForUpdate 再次评估c>表达式。如果它仍然是真的,再次执行 Statement ,那么 ForUpdate ;直到表达式为假。



您可以按如下方式将其重构为一个while循环:

  ForInit; 
while(Expression){
Statement;
ForUpdate;



$ b $为了将这个模式应用到一个真正的for循环,只需要替换如上所述。



以上例子:


  • ForInit => int i = 0
  • / code> => i < 5

  • ForUpdate => i ++

  • 语句 => list [i] = i + 2;


    我= 0;
    while(i <5){
    list [i] = i + 2;
    i ++;
    }


I am creating an array program. I am practicing how to convert for loops to while loops, but I cannot grasp the concept.

If I have the for loop:

int [] list = new int [5];

for (int i = 0; i < 5; i++) {
    list [i] = i + 2;
}

How would I make it a while loop?

Here's my attempt

int [] list = new int [5];
int i = 0;

while (i<5) {
    list [i] = i + 2;
    i++;
}
System.out.print(list[i] + " ");

This is what I think should be done, but it comes up as an error in my computer.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Arrays2.main(Arrays2.java:21)

This is line 21

System.out.print(list[i] + " ");

解决方案

The general structure of a basic for statement is:

for ( ForInit ; Expression ; ForUpdate ) Statement

  • ForInit is the initializer. It is run first to set up variables etc.
  • Expression is a boolean condition to check to see if Statement should be run
  • Statement is the block of code to be run if Expression is true
  • ForUpdate is run after the Statement to e.g. update variables as necessary

After ForUpdate has been run, Expression is evaluated again. If it is still true, Statement is executed again, then ForUpdate; repeat this until Expression is false.

You can restructure this as a while loop as follows:

ForInit;
while (Expression) {
  Statement;
  ForUpdate;
}

In order to apply this pattern to a "real" for loop, just substitute your blocks as described above.

For your example above:

  • ForInit => int i = 0
  • Expression => i < 5
  • ForUpdate => i++
  • Statement => list [i] = i + 2;

Putting it together:

int i = 0;
while (i < 5) {
  list[i] = i + 2;
  i++;
}

这篇关于我如何将这个for循环转换为while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆