public class Test { public static void main(String args[]){ int x = 10; if( x < 20 ){ System.out.print("这是 if 语句"); } } }
if-else结构
1 2 3 4 5 6 7 8 9 10 11 12
public class Test { public static void main(String args[]){ int x = 30; if( x < 20 ){ System.out.print("这是 if 语句"); }else{ System.out.print("这是 else 语句"); } } }
if-else嵌套
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassTest { publicstaticvoidmain(String args[]){ intx=30; inty=10; if( x == 30 ){ if( y == 10 ){ System.out.print("X = 30 and Y = 10"); } } } }
switch
switch 语句中的变量类型可以是: byte、short、int 或者 char。
从 Java SE 7 开始,switch 支持字符串 String 类型了,同时 case 标签必须为字符串常量或字面量。模式使用String的hashCode作为匹配方法。
switch 不支持 long、float、double,是因为 switch 的设计初衷是对那些只有少数几个值的类型进行等值判断,如果值过于复杂,那么还是用 if 比较合适。
publicclassTest { publicstaticvoidmain(String[] args) { intx=10; while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } }
do…while 循环
对于 while 语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次。
do…while 循环和 while 循环相似,不同的是,do…while 循环至少会执行一次。
1 2 3 4 5 6 7 8 9 10 11
publicclassTest { publicstaticvoidmain(String[] args){ intx=10; do{ System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } }
for循环
虽然所有循环结构都可以用 while 或者 do…while表示,但 Java 提供了另一种语句 —— for 循环,使一些循环结构变得更加简单。
for循环执行的次数是在执行前就确定的。语法格式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
for(初始化; 布尔表达式; 更新) { //代码语句 }
publicclassTest { publicstaticvoidmain(String[] args) { for(intx=10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } }