一、switch…case
1.代码
public class Model3 {
public static void main(String[] args) {
//switch case,匹配
Scanner sc = new Scanner(System.in);
System.out.println("请输入值:");
int a = sc.nextInt();
switch(a) {
case 1:
//当a == 1时从该行开始运行
System.out.println(1);
break;//结束所在的代码块儿,即switch
case 2:
System.out.println(2);
break;
default:
//当其他项都不匹配时运行的代码
System.out.println("您输入的值不合法!");
break;
}
sc.close();
}
}
2.可以匹配byte,short,int,char,String,枚举
3.多行匹配
switch(a) {
//输入1或2都是输出去a班
case 1:
case 2:
System.out.println("你输入的班级是"+a+",要去a班");
break;
//输入3或4都是输出去b班
case 3:
case 4:
System.out.println("你输入的班级是"+a+",要去b班");
break;
//输入其他值去c班
default:
System.out.println("您属于其他班,去c班");
break;
}
4.若switch中是char类型,case值如果是int,则匹配的就是ASCII
5.与if的区别
if()中只需要boolean类型,不关心类型和数值,可范围性判断
switch需要匹配指定类型,只能单个匹配
二、循环
1.while循环
public class Model5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/* 从1打印到10 */
//while循环,条件是boolean类型
int i = 1;
while(i <= 10) {
//重复做的事
System.out.print(i+",");
i++;
}
}
}
2.死循环
条件不会被中断的循环(循环条件一直成立)
3.do…while循环
至少执行一次,先执行,后判断
public class Model8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 1;
do {
System.out.println(a);
a++;
}while(a<21);
}
}
4.for循环
小括号需要三个表达式,可以不写,但是必须有两个分号
public class Model11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*for循环打印1-20*/
for(int i=1;i<=20;i++) {
//循环体
System.out.print(i+",");
}
}
}