首页 > 代码库 > Java入门——选择与循环语句
Java入门——选择与循环语句
If...else...语句
1 public class IfDemo { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 int x=20; 9 int y=12;10 System.out.println("******比较开始******");11 if(x<y){12 System.out.println("x比y小!");13 }else if(x>y){14 System.out.println("x比y大!");15 }else{16 System.out.println("x和y相等!");17 }18 System.out.println("******比较完成******");19 }
结果如下:
******比较开始******x比y大!******比较完成******
Swich语句
-
1 public class SwitchDemo { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 int x=3; 9 int y=6;10 char oper=‘+‘;11 switch(oper){12 case ‘+‘:{13 System.out.println("x+y="+(x+y));14 break;//退出switch15 }16 case ‘-‘:{17 System.out.println("x-y="+(x-y));18 break;19 }20 case ‘*‘:{21 System.out.println("x*y="+(x*y));22 break;23 }24 case ‘/‘:{25 System.out.println("x/y="+(x/y));26 break;27 }28 default:{29 System.out.println("未知的操作!");30 break;31 }32 }33 }34 35 }
如果不设置break语句,程序不会跳出switch
while
1 public class WhileDemo { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 int x=1; 9 int sum=0;10 while(x<=10){11 sum+=x;12 x++;13 }14 System.out.println("1到10的累加和为:"+sum);15 }16 17 }
while是循环语句,也是条件判断语句。当实现不知道循环该执行多少次的时候,就要用到while循环。
do...while
1 public class DoWhileDemo { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 int x=1; 9 int sum=0;10 do{11 sum+=x;12 x++;13 }while(x<=10);14 System.out.println("1到10的和为:"+sum);15 }16 17 }
do...while...循环和while循环的操作是一样的,但是会至少执行一次。
for
1 public class ForDemo { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 int sum=0; 9 for(int x=1;x<=10;x++){10 sum+=x;11 }12 System.out.println("1到10的和为:");13 }14 15 }
(赋值初值;判断条件;赋值增减量)
循环的嵌套
1 public class ForNestedDemo { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 for(int i=1;i<=9;i++){ 9 for(int j=1;j<=i;j++){10 System.out.print(i+"*"+j+"="+(i*j)+"\t");11 }12 System.out.print("\n");13 }14 }15 16 }
结果如下:
1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 4*1=4 4*2=8 4*3=12 4*4=16 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
循环的中断
- break语句可以强迫程序中断循环,当执行到break时,程序就会离开循环;
- continue语句可以迫使程序跳到循环的起始处;
Java入门——选择与循环语句
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。