一、流程概述与顺序结构
//顺序结构 public class Demo01Sequence{ public static void main(String[] args){ System.out.println("今天天气不错"); System.out.println("挺风和日丽的"); System.out.println("我们下午没睡"); System.out.println("这的确挺爽的"); } }
二、选择结构_单if语句
// 单if语句 public class Dem02If{ public static void main(String[] args){ public static void main(String[] args){ System.out.println("今天天气不错,正在压马路...突然发现一个快乐的地方:网吧"); int age = 19; if (age >= 18){ System.out.println("进入网吧,开始high!"); System.out.println("遇到了一群猪队友,开始骂街。"); System.out.println("感觉不爽,结账走人。"); } System.out.println("回家吃饭"); } } }
三、选择结构_标准if-else语句
// 标准的if-else语句 public class Demo03IfElse{ public static void main(String[] args){ int num = 666; if (num % 2 == 0){ // 如果除以2能够余数为0,说明是偶数 System.out.println("偶数"); } else { System.out.println("奇数"); } } }
四、选择结构_扩展if-else语句
//x和y的关系满足如下: //如果x >= 3,那么y = 2x + 1; //如果-1 < x < 3,那么y = 2x; //如果x <= -1,那么y = 2x -1; public class Demo04IfElseExt{ public static void main(String[] args){ int x = 10; int y; if (x >= 3){ y = 2 * x + 1; } else if (-1 < x && x <3){ y = 2 * x; } else { y = 2 * x -1; } System.out.println("结果是:" + y); } }
五、练习_用if语句实现考试成绩
//考试成绩代码 public class Demo05IfElsePractise{ public static void main(String[] args){ int score = 98; if (score >= 90 && score <= 100) { System.out.println("优秀"); } else if (score >= 80 && score < 90) { System.out.println("好"); } else if (score >= 70 && score < 80) { System.out.println("良"); } else if (score >= 60 && score < 70) { System.out.println("及格"); } else if (score >= 0 && score < 60) { System.out.println("不及格"); } else { System.out.println("数据错误"); } } }