0%

Java/Java学习记录

分支结构

if

switch

语法结构

1
2
3
4
5
6
7
switch (表达式) { case1:
语句组1 case2:
语句组2 case3:
语句组3 ...
case 判断值n: 语句组n
default: 语句组n+1
}

switch语句中“表达式”计算结果只能是int,byte,short,char类型,不能是long更不能是其他的类型。

循环结构

while

do-while

for

for-each语句

Java 5之后提供了一种专门用于遍历集合的for循环——for-each循环。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Test {
public static void main (String[]args) {

int[ ]numbers = {1,3,5,7,9};
System.out.printf("for-each 语句%n");
for (int number : numbers) {
System.out.printf("%d%n",number);
}
}
}
/*
* 输出结果:
*
for-each 语句
1
3
5
7
9
*/

跳转语句

跳转语句能够改变程序的执行顺序,可以实现程序的跳转。

break

break;不带标签

break label;带标签

默认情况下,break只会跳出最近的内循环。如果要跳出代码第1行的外循环, 可以为外循环添加一个标签,注意在定义标签的时候后面跟一个冒号

添加标签对于多层嵌套循环是很有必要的,适 当使用可以提高程序的执行效率。

continue

带标签

不带标签

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package nianchu;

public class Test {
public static void main (String[]args) {
int a=5,b=2;
x1:for(a=0;a<3;a++) {
for(b=0;b<3;b++) {
if(a==b) {
continue x1;
}
System.out.printf("(%d,%d)",a,b);
}
}

}
}
/*
* 输出结果:
*
(1,0)(2,0)(2,1)
*/

小技巧

输出时可以用+号将要输出的两部分连在一起

实例:

1
2
3
4
5
public class Test {
public static void main (String[]args) {
System.out.println("C" + "LOVE" + "L");
}
}

获取数组的长度

numbers.length

1
printf主要是继承了C语言的printf的一些特性,可以进行格式化输出
1
print就是一般的标准输出,但是不换行
1
println和print基本没什么差别,就是最后会换行