Java for循环
原文: https://javabeginnerstutorial.com/core-java-tutorial/java-for-loop/
Java for循环和增强的for循环是一种控制流语句,它提供了一种紧凑的方法来迭代值范围。 循环重复遍历代码,直到满足特定条件为止。
在此期间,Java for循环具有不同类型。
for循环- 增强
for循环或foreach
for循环
for循环是 3 个表达式的组合,需要理解才能有效地使用for循环。
- 初始化表达式初始化循环; 它会在循环开始时执行一次。
- 终止表达式用于停止循环。 每次迭代都会对它进行求值,并且当终止表达式的求值结果为
false时,循环终止。 - 通过循环的每次迭代后,将调用递增/递减表达式。
循环的语法
for(Initialization; Termination; Increment/Decrement){//Code to execute in loop}
for循环示例
public class for_loop {public static void main(String[] args) {for (int i = 0; i < 4; i++) {System.out.println("Value of i: " + i);}int j;//declare variable outside for loop if needed beyond loopfor (j = 4; j < 8; j++) {System.out.println("Value of j: " + j);}int k = 8;for (; k < 12; k++) {System.out.println("Value of k: " + k);}}}
上述程序的输出
Value of i: 0Value of i: 1Value of i: 2Value of i: 3Value of j: 4Value of j: 5Value of j: 6Value of j: 7Value of k: 8Value of k: 9Value of k: 10Value of k: 11
这里的代码在初始化表达式中声明了一个int变量i。 变量i的范围从其声明扩展到for语句块的末尾,因此它也可以在终止和增量表达式中使用。
如果循环外不需要控制for语句的变量,则最好在初始化表达式中声明该变量。 如您在使用int i变量的第一个for循环中所看到的。 在初始化表达式中声明它们会限制它们的寿命并减少错误。
名称i,j和k通常用于控制for循环。
请注意,
for循环的三个表达式是可选的。 因此,下面的两个代码都是有效的,尽管它将创建一个无限循环
for (; ; k++) {System.out.println("Infinite loop");}
for (; ; ) {System.out.println("Infinite loop");}
增强的for循环
增强的for循环是for循环的另一种形式。 它是 Java 5 中引入的,它是一种更简单的方法来迭代集合和数组的所有元素。 它可以使您的循环更紧凑,更易于阅读。
增强的for循环语法
for(DataType obj: array/collection){}
增强的for循环示例
import java.util.Arrays;import java.util.List;public class for_loop {public static void main(String[] args) {//enhanced for loopString[] array = {"Hello ", "Hi ", "How ", "are ", "you?"};List<String> list = Arrays.asList(array);for (String str : array) {System.out.print(str);}System.out.println("\n");for (String str : list) {System.out.print(str);}}}
上面代码的输出是
Hello Hi How are you?Hello Hi How are you?
增强了循环遍历给定集合或数组中的每个对象,将对象存储在变量中和执行循环的主体。
建议尽可能使用增强的
for循环。
在增强的 for 循环中找不到当前索引。 在需要索引号的情况下,可以使用旧的for循环,也可以尝试以下替代方法来获取索引号。
import java.util.Arrays;import java.util.List;public class for_loop {public static void main(String[] args) {//enhanced for loopString[] array = {"Hello ", "Hi ", "How ", "are ", "you?"};List<String> list = Arrays.asList(array);int index = 0;for (String str : array) {System.out.print(str);System.out.println("Current Index :" + index++);}System.out.println("\n");for (String str : list) {System.out.print(str);System.out.println("Current Index: " + list.indexOf(str));}}}
代码输出
Hello Current Index :0Hi Current Index :1How Current Index :2are Current Index :3you?Current Index :4Hello Current Index: 0Hi Current Index: 1How Current Index: 2are Current Index: 3you?Current Index: 4
可以在此处找到for循环的代码。