if语句
- 单if语句
1. // 格式 2. 3. if(关系表达式){ 4. 语句体; 5. } 6. 7. // 示例代码 8. 9. /** 10. * @Time: 2021/5/1 11. * @Author: 大海 12. **/ 13. public class test05 { 14. 15. public static void main(String[] args) { 16. System.out.println("前面有家网吧!"); 17. int age = 19; 18. if (age >= 18) { 19. System.out.println("上网,嗨起来!!!"); 20. } 21. System.out.println("回家吃饭!"); 22. } 23. 24. }
- if...else语句
1. // 格式 2. 3. if(关系表达式){ 4. 语句体1; 5. }else{语句体2;} 6. 7. 8. // 示例代码 9. 10. /** 11. * @Time: 2021/5/1 12. * @Author: 大海 13. **/ 14. public class test06 { 15. public static void main(String[] args) { 16. int a = 22; 17. if (a % 2 == 0) { 18. System.out.println("a是偶数"); 19. } else { 20. System.out.println("a是奇数"); 21. } 22. System.out.println("程序结束!"); 23. } 24. 25. 26. }
- if...else if...else语句
1. // 格式 2. 3. if(判断条件1){ 4. 执行语句1; 5. }else if(判断条件2){ 6. 执行语句2; 7. ... 8. }else if(判断条件n){ 9. 执行语句n;} 10. else{ 11. 执行语句n+1;} 12. 13. // 示例代码 14. /** 15. * @Time: 2021/5/1 16. * @Author: 大海 17. **/ 18. public class test07 { 19. public static void main(String[] args) { 20. int score = 99; 21. if (score < 0 || score > 100) { 22. System.out.println("分数不正确!"); 23. } else if (score >= 90 && score <= 100) { 24. System.out.println("成绩优秀!!!"); 25. } else if (score >= 80 && score <= 89) { 26. System.out.println("成绩良好!!"); 27. } else if (score >= 60 && score <= 79) { 28. System.out.println("成绩及格!"); 29. } else { 30. System.out.println("成绩不及格?"); 31. } 32. } 33. 34. 35. }
switch语句
注意事项:
- 多个case后面的数值不可以重复。
- switch后面小括号当中只能是下列数据类型:
基本数据类型:byte/short/char/int
引用数据类型:String字符串、enum枚举
- switch语句格式可以很灵活:前后顺序可以颠倒,而且break语句还可以省略。
1. // 格式 2. switch(表达式){ 3. case常量值1: 4. 语句体1; 5. break; 6. case常量值2: 7. 语句体2; 8. break; 9. ... 10. default: 11. 语句体n+1; 12. break; 13. } 14. 15. // 示例代码 16. 17. /** 18. * @Time: 2021/5/1 19. * @Author: 大海 20. **/ 21. public class test08 { 22. public static void main(String[] args) { 23. int num = 4; 24. switch (num) { 25. case 1: 26. System.out.println("星期1"); 27. break; 28. case 2: 29. System.out.println("星期2"); 30. break; 31. case 3: 32. System.out.println("星期3"); 33. break; 34. case 4: 35. System.out.println("星期4"); 36. break; 37. case 5: 38. System.out.println("星期5"); 39. break; 40. case 6: 41. System.out.println("星期6"); 42. break; 43. case 7: 44. System.out.println("星期7"); 45. break; 46. default: 47. System.out.println("数据错误!"); 48. } 49. } 50. 51. 52. }
case穿透性
1. /** 2. * @Time: 2021/5/1 3. * @Author: 大海 4. **/ 5. 6. public class test09 { 7. public static void main(String[] args) { 8. //匹配哪一个case就从哪一个位置向下执行,如果未写break,将穿透case向下执行,直到遇到了break或者整体结束为止。 9. int num = 2; 10. switch (num) { 11. case 1: 12. System.out.println("你好!"); 13. break; 14. case 2: 15. System.out.println("我好!"); 16. // break; 17. case 3: 18. System.out.println("他好!"); 19. break; 20. default: 21. System.out.println("大家好!"); 22. break; 23. } 24. } 25. 26. }