标题: Java基础循环 判断笔记 [打印本页] 作者: 只要铭记 时间: 2018-6-15 23:11 标题: Java基础循环 判断笔记 1、顺序结构:按循序从上到下进行
2、选择结构:
2.1判断语句:单if语句: true就执行语句体,false就结束
//满足就执行if语句 不满足就跳过
if(判断语句(关系表达式)){
语句体;
}
public class Demo02If{
public static void main(String[] args){
System.out.pringln("今天天气不错,看到网吧");
int age = 16;
if (age >= 18){
System.out.println("玩");
}
System.out.println("回家");
}
}
2.2、if····else语句:true执行语句体1 false 执行语句体2 二者选其一
if(判断语句(关系表达式){
语句体1;
}else {
语句体2;
}
int num = 13;
if (num % 2== 0){//如果除以2 为0 说明是偶数
System.out.println("偶数");
}else {
System.out.println("奇数");
}
2.3、if```else 拓展格式 可以实现多者选其一
if (判断条件1){
执行语句1;
} else if(判断条件2){
执行语句2;
}
···
} else if(判断语句n){
执行语句n;
}else {
语句体n+1;
}
public class Domo01{
public static void main(String[] args){
int mouth = 2;
if (mouth ==1){
System.out.println("星期一");
}else if (mouth == 2){
System.out.println("星期二");
}else if (mouth == 3){
System.out.println("星期三");
}else if (mouth == 4){
System.out.println("星期四");
}else if (mouth == 5){
System.out.println("星期五");
}else if (mouth == 6){
System.out.println("星期六");
}else if (mouth == 7){
System.out.println("星期日");
}else {
System.out.println("输入错误");
}
}
}
2.4、选择语句、、、switch
switch (表达式){
case 常量值1:
语句体1
break;
case 常量值2:
语句体2
break;
...
default:
语句体n+1;
break;//可以省略 建议不要省略
}
public class Domo02{
public static void main(String[] args){
int num = 5;
switch(num){
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("输入错误");break;
}
}
}
注意事项:
1、多个case后面的常量值不能重复
2、switch后面的小括号当中只能是下列类型
基本数据类型: byte short char int
引用数据类型: String字符串 enum枚举
3、switch语句格式可以很灵活: 前后顺序可以颠倒,而且break语句还可以省略。
“匹配哪一个case就送哪一个位置向下执行,直到遇到break或者整体结束为止”
1、for循环语句****(知道次数的)*****
for(初始化表达式1;布尔表达式2;步进表达式3){
循环体4
}
执行顺序 1--2--4--3-->243-243-243 不满足为止
public class Demo03{
public static void main(String[] args){
for (int i = 1;i <= 100;i++){
System.out.println("我错啦"+ i);
}
System.out.println("程序停止");
}
}
while 循环
1、标准格式;满足-->循环体 不满足-->结束
格式
while (条件判断){
循环体
}
2、拓展格式:
初始化语句;
while(条件判断){
循环体;
步进语句;
}
public class Demo{
public static void main(String[] args){
for (int i = 1; i <=10; i++){
System.out.println("w cuo la ");
}
int i = 1// 1 初始化语句:
while (i <= 10){//条件判断
System.out.println("w cuo la ");//循环体
i++;
}
}
}
1、特征: 不知道使用次数
3、do...while 循环 *****************
标准格式
do {
循环体
}while(条件判断);
拓展格式:*********************
初始化语句
do {
循环体
步进语句
}while (条件判断);
int i = 1;
do{
System.out.println();
i++;
} while (i <= 10);
*********至少循环一次*********
题目:sun求出1-100之间的偶数和
public class Demo{
public static void main(String[] args){
int sun = 0;// 用来累加的存钱罐
for (int i = 1;i <= 10; i++){
if (i %2 == 0){
sum += i;
}
}
}
}
3种循环的区别
1、 如果条件判断从来没有满足过,那么for和while循环
将会执行0次, 但是do..while会至少执行一次
2、 for循环的变量在小括号当中定义,只有循环内部才能使用
while和do..while循环初始化语句本来就在外面,所以出来可以继续使用