一、循环结构:
Java中有三种主要的循环结构:
- while 循环
- do…while 循环
- for 循环
1. while 循环
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
2. do…while循环
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
while 与do …while区别
while:如果不满足条件,则不能进入循环。
do…while:至少会执行一次。
3. for循环
public class Test {
public static void main(String args[]) {
//最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
for 和 while区别
for循环的初始化变量,在循环结束后,不可以被访问。
while循环的初始化变量,是可以被继续使用的。
如果初始化变量,后面还要继续访问,就使用while,否则,推荐使用for。for(int x=1; x<=10; x++){ System.out.println("爱生活,爱Java"); } //这里的x无法继续访问 //System.out.println(x); System.out.println("-----------------"); int y = 1; while(y<=10) { System.out.println("爱生活,爱Java"); y++; } System.out.println(y); }
【补充】Java 增强 for 循环
/** *for(声明语句 : 表达式){ //代码句子 } //声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。 表达式:表达式是要访问的数组名,或者是返回值为数组的方法。 **/ public class Test { public static void main(String args[]){ int [] numbers = { 10, 20, 30, 40, 50}; for(int x : numbers ){ System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names ={ "James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } }
终止循环关键字
1.break
break 主要用在循环语句或者 switch 语句中,用来跳出整个语句块。
break 跳出最里层的循环,并且继续执行该循环下面的语句。
2.continue
continue 适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。
二、条件语句
1.if…else
public class Test {
public static void main(String args[]){
int x = 30;
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("这是 else 语句");
}
}
}
2.switch case
switch(expression){
case value1 :
//语句
break; //可选
case value2 :
//语句
break; //可选
//你可以有任意数量的case语句
default : //可选
//语句
}
switch(expression){
case value1 :
case value2 :
//语句
break; //可选
//你可以有任意数量的case语句
default : //可选
//语句
}
【注】
- switch 语句中的变量类型可以是: byte、short、int 或者 char。
从 Java SE 7 开始,switch 支持字符串 String 类型了,同时 case 标签必须为字符串常量或字面量。 - switch 语句可以拥有多个 case 语句。每个 case 后面跟一个要比较的值和冒号。
- case 语句中的值的数据类型必须与变量的数据类型相同,而且只能是常量或者字面常量。
- 当变量的值与 case 语句的值相等时,那么 case 语句之后的语句开始执行,直到 break 语句出现才会跳出 switch 语句。
当遇到 break 语句时,switch 语句终止。程序跳转到 switch 语句后面的语句执行。case 语句不必须要包含 break 语句。如果没有 break 语句出现,程序会继续执行下一条 case 语句,直到出现 break 语句。 - switch 语句可以包含一个 default 分支,该分支一般是 switch 语句的最后一个分支(可以在任何位置,但建议在最后一个)。default 在没有 case 语句的值和变量值相等的时候执行。default 分支不需要 break 语句。
switch和if…else
所有switch可用if…else代替,但不会所有if…else可switch代替
switch效率高,能用的地方一定要用