if-else的使用
@Test
public void test1() {
Scanner scanner = new Scanner(System.in);
int score = scanner.nextInt();
//卫语句
//非法输入直接返回
if (score > 100 || score < 0) {
System.out.println("请输入正确的数值");
return;
}
if (score >= 90 && score <= 100) {
System.out.println("优秀");
} else if (score >= 80 && score <= 90) {
System.out.println("良好");
} else if (score >= 60 && score <= 80) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
}
上述是一个简单的输入成绩反馈等级的代码段,卫语句即:
if (score > 100 || score < 0) {
System.out.println("请输入正确的数值");
return;
}
判断输入非法后直接返回,不必再继续往下运行;
if ( case1 || case2 )
if ( case1 && case2 )
case1和case2均只能为boolen类型数据,这点和c不同,c中if(1)等同于if(true);
&和| 为布尔运算符,&&和|| 为条件布尔运算符
int a = 0,b = 1;
if(a > 0 && ++b == 2){
}
System.out.println(b);//此时输出b的值为 1 ;
if(a > 0 & ++b == 2){
}
System.out.println(b);//此时输出b的值为 2 ;
&&运算符在前半部分判断为错误时,不会继续判断后半部分;
&运算符在前半部分判断为错误时,会继续判断后半部分;
||与|运算符同理
switch-case的使用
@Test
public void test2(){
Scanner scanner = new Scanner(System.in);
int month = scanner.nextInt();
switch (month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println("31天");
break;
case 2:
System.out.println("28/29天");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println("30天");
break;
default:
System.out.println("输入错误");
}
}
上述代码是一个输入月份判断天数的片段。
switch适用于判断条件只取某几个值的情况,每个case代表了一个取值情况,在switch-case中如果没有运行到 break; 语句就会一直运行下去知道出现 break; 或者运行结束。