【问题标题】:For loop to While loop JavaFor 循环到 While 循环 Java
【发布时间】:2021-03-27 19:47:43
【问题描述】:

如何将此代码更改为 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");
        }
    }
}

【问题讨论】:

  • 只要获取数组的迭代器,只要hasNext()返回true就循环,在循环中使用next()获取元素。或者使用索引。

标签: java arrays for-loop while-loop


【解决方案1】:
    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
    }

输出:

10
20

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 2018-11-05
    • 1970-01-01
    • 2019-11-10
    相关资源
    最近更新 更多