Java代码有三种执行结构流程,顺序结构、分支结构、循环结构
顺序结构
顺序结构是最简单的代码执行结构,从代码开始逐步执行每一句代码到结束
1 public class C { 2 public static void main(String[] args){ 3 4 String name = "白客C"; 5 String str = "你好,"; 6 7 System.out.printf(str+name); 8 } 9 }
分支结构
分支结构需要用到条件语句if、switch
if多分支语句
1 import java.io.*; 2 3 public class C { 4 public static void main(String[] args){ 5 6 //实例1 7 float f =1.33f; 8 if(!(f % 1 == f)) 9 { 10 System.out.println("是小数"); 11 } 12 13 //实例2 14 int a=2, b=3; 15 if(a>b) 16 { 17 System.out.println("a大于b"); 18 } 19 else 20 { 21 System.out.println("a小于b"); 22 } 23 24 25 //实例3 26 try{ 27 InputStreamReader isr = new InputStreamReader(System.in); 28 BufferedReader br = new BufferedReader(isr); 29 30 System.out.printf("请输入您的分数:"); 31 String str = br.readLine(); 32 int num = Integer.parseInt(str); 33 34 if(num <= 100 && num >= 90) 35 { 36 System.out.printf("优秀"); 37 }else if(num < 90 && num >= 80) 38 { 39 System.out.printf("良好"); 40 }else if(num < 80 && num >= 70) 41 { 42 System.out.printf("中"); 43 }else if(num < 70 && num >= 60) 44 { 45 System.out.printf("及格"); 46 }else 47 { 48 System.out.printf("不及格"); 49 } 50 51 }catch (Exception e){ 52 53 } 54 } 55 }
switch语句
switch语句与if语句的实例3功能一样
1 import java.io.*; 2 3 public class C { 4 public static void main(String[] args){ 5 6 try{ 7 InputStreamReader isr = new InputStreamReader(System.in); 8 BufferedReader br = new BufferedReader(isr); 9 10 System.out.printf("请输入您的分数:"); 11 String str = br.readLine(); 12 int num = Integer.parseInt(str); 13 14 switch (num % 10) 15 { 16 case 10: 17 case 9: 18 System.out.printf("优秀"); 19 break; 20 case 8: 21 System.out.printf("良好"); 22 break; 23 case 7: 24 System.out.printf("中"); 25 break; 26 case 6: 27 System.out.printf("及格"); 28 break; 29 default: 30 System.out.printf("不及格"); 31 } 32 }catch (Exception e){ 33 34 } 35 } 36 }
循环结构
循环结构就重复执行某段语句块,有for循环语句、while循环语句、do-while循环语句
for循环语句
1 public class C { 2 public static void main(String[] args){ 3 int num = 0; 4 for(int i = 1 ; i <= 100 ; i++) 5 { 6 num += i; 7 } 8 String str = String.valueOf(num); 9 System.out.print("i=" + str ); 10 } 11 }
while循环语句
1 public class C { 2 public static void main(String[] args){ 3 int i = 1; 4 int num = 0; 5 while ( i <= 100 ) 6 { 7 num += i; 8 i++; 9 } 10 String str = String.valueOf(num); 11 System.out.print("i=" + str ); 12 } 13 }
do-while循环语句
do-while会先执行一次
1 public class C { 2 public static void main(String[] args){ 3 int i = 1; 4 int num = 0; 5 6 do{ 7 num += i; 8 i++; 9 }while (i<=100); 10 11 String str = String.valueOf(num); 12 System.out.print("i=" + str ); 13 } 14 }
原文:https://www.cnblogs.com/beekc/p/12315628.html