开发手册 欢迎您!
软件开发者资料库

Java for循环之前声明for循环变量的写法及示例代码

Java 中一般for循环的变量声明是在for关键字后括号中,但有可能有些情况,不能在括号中声明,本文主要介绍的for循环变量的声明在循环之前,来写for循环的方法及示例代码。

1、将for语句的第一部分留空

int v = 0;for (; v < 2; v++) {    System.out.println(v);Thread.sleep(1000); }

2、while (true)循环相同的写法

int v=1;
for (;;) {
System.out.println(v);Thread.sleep(1000); }

3、多个变量的写法

int j = 0;
for (int k = 0; k < 10; k++, j++) {
}

或者

int j = 0;
for (int k = 0; k < 10 || j < 10; k++, j++) {
}

或者

for (int k = 0, j = 0; k < 10 || j < 10; k++, j++) {
}

4、简洁的写法

public class Main {
public static void main(String[] args) {
int[] integers = { 10, 20, 30 };
for (int x : integers) {
System.out.println(x);
}
}
}

5、for语句的一般形式

官方文档https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

for (initialization; termination; increment) {
statement(s)
}