繁体   English   中英

For 循环到 While 循环 Java

[英]For loop to While loop Java

我怎样才能将此代码更改为while 循环 我会把它转换成一个while循环

public class example {
    public static void main(String[] args) {
        int [] numbers={10, 20, 30, 40, 50};
        for(int x:numbers){
            if(x==30){
                break;
            }
            System.out.print(x);
            System.out.print("\n");
        }
    }
}
    int[] numbers = {10, 20, 30, 40, 50};    
    int i = 0;                               
    while (i < numbers.length) {             //iterating till the last element in the array on index
        int currentValue = numbers[i];       //storing in a variable for reuse while printing the value
        if (currentValue == 30) {            //conditional break in the loop as OP
            break;
        }
        System.out.println(currentValue);    //printing each element in a newline
        i++;                                 //incrementing the counter to the next index
    }

Output:

10
20

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM