Java中三大流程结构:顺序 选择 循环
顺序:从上往下依次执行
选择:if语句 if_else 多重,嵌套 if-else switch(整型 字符型 字符串)语句
循环: while do_while for 嵌套循环
break:结束当前循环
continue:结束当前循环,但会执行下一次循环
if 选择结构
1 if (x > 0) { 2 y = 2 * x + 1; 3 } else { 4 y = x + 5; 5 } 6
switch 选择结构
switch(week) { case 1: System.out.println("今天是星期一"); break; case 2: System.out.println("今天是星期二"); break; case 3: System.out.println("今天是星期三"); break; case 4: System.out.println("今天是星期四"); break; case 5: System.out.println("今天是星期五"); break; case 6: System.out.println("今天是星期六"); break; case 7: System.out.println("今天是星期日"); break; default: System.out.println("您输入的数字是无效的"); }
if-else 多重选择
//商品折扣 public void disCount(double a) { if(a < 100) { System.out.println("没有达到打折标准,原价为:" + a); }else if(a >= 200) { double b = a * 0.85; System.out.println("达到打折标准,打8.5折.原价为:" + a + "折后价格为:" + b); }else { double c = a * 0.95; System.out.println("达到打折标准,打9.5折.原价为:" + a + "折后价格为:" + c); } }
for 循环结构
public static void main(String[] args) { //统计一个字符串中'a' 'A'出现的次数 char[] a = {'a','b','A','A','c','a','g','h'}; int n = 0; for(int i = 0;i < a.length;i++) { boolean x = a[i] == 'a'; boolean y = a[i] == 'A'; if(x || y) { n++; } } System.out.println("字符串中'a' 'A'出现的次数为:" + n); //char[][] ch =new char[][]; 错误形式 }
while 循环
public static void main(String[] args) { //求1到1000的累加和 int a = 1; int sum = 0; while(a <= 1000) { sum += a; a++; } System.out.println(sum); }
多重while循环:
public static void main(String[] args) { //用while循环输出10行10列的星星 int i = 1; int j = 1; while(j <= 10) { while(i <= 10) { System.out.print("★" + " "); i++; } System.out.println(); j++; i = 1;//重新给i赋值 } }