循环语句

  1. for 语句
  2. while 语句
  3. do-while 语句

for 语句

1
2
3
4
5
6
7
8
9
10
11
12
13
public class For01 {
public static void main(String[] args) {
for (int i = 1; i < 100; i++) {
if (i == 2) {
coutinue; // 跳过本次循环
}
System.out.printLn(i);
if (i == 5) {
break; // 提前结束循环
}
}
}
}

while 语句

1
2
3
4
5
6
7
8
9
public class While01 {
public static void main(String[] args) {
int i = 1;
While (i <= 10) {
System.out.printLn(i); // 执行 10 次
i += 1;
}
}
}

do-while 语句

1
2
3
4
5
6
7
8
public class DoWhile01 {
public static void main(String[] args) {
int i = 1;
do {
System.out.printLn(i); // 执行一次
} while (i < 0);
}
}

while 的区别,do-while 至少执行一次

数组

数据是一个可以储存相同数据类型的数据的集合

注意:数组有固定的大小,一旦被创建,无法修改大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Array01 {
public static void main(String[] args) {
// 声明
int[] array;
int array1[];
// 初始化
array = new int[5]; // 默认值:[0,0,0,0,0]
array[0] = 10; // [10,0,0,0,0]
array[5] = 10; // 报错

// 声明并初始化
int[] array2 = new int[]{10,20,30,40,50};
int[] array3 = new int[5]{10,20,30,40,50}; // 报错
int[] array4 = {20,30};
}
}

方法

1
2
3
4
5
6
7
8
9
10
11
12
public class Method01 {
public static void main(String[] args) {
int m = Method01.sum(1, 2);
int m = Method01.sum(10, 20);
int m = Method01.sum(100, 200);
}
public static int sum(int a, int b) {
int c = a + b;
System.out.printLn(c);
return c;
}
}