java 数组 循环,我如何把这个循环到Java中的while循环(使用数组)?

So I have to do an assignment for school and I am creating an arrays 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?

also, sorry this is my first time using the site :)

edit: 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.

edit #2:

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

The print code:

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

//this is line 21^^

解决方案

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++;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值