class IfTest{
public static void main(String[]args){
int hearBreats = 79;
if(hearBeats<60 || heartBeats>100){
System.out.println("需要做进一步检查");
}
System.out.println("检查结束");
}
}
定义三个int型变量并赋值,使用if-else获取这三个数中的较大值
int num1 = 10,num2 = 21,num3 = -21;
int max;
if(num1>=num2 && num1>=num3){
max = num1;
}else if(num2>=num1 && num2>=num3){
max = num2;
}else{
max = num3;
}
System.out.println("三个数中的最大值为:"+max);
题目一
import java.util.Scanner;//导包
class IfTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);//Scanner实例化
System.out.println("请输入期末成绩:");
int score = scan.nextInt();
if(score == 100){
System.out.println("奖励一辆BMW");
}else if(score > 80 && score <= 99){
System.out.println("奖励一ipone xs max");
}else if(score >= 60 && score <= 80){
System.out.println("奖励一IPAD");
}else{
System.out.println("什么奖励都没有");
}
}
}
题目二
int dogAge = 6;
if(dogAge >= 0 && dogAge <= 2){
System.out.println("相当于人的年龄:"+dogAge*10.5);
}else if(dogAge>2){
System.out.println("相当于人的年龄:"+(2*10.5+(dogAge-2)*4));
}else{
System.out.println("相当于人的年龄:"+dogAge*10.5);
}
题目三
分支语句2:
switch-case结构
/*1.根据switch表达式中的值,依次匹配各个case中的常量。
一旦匹配成功,则进入相应case结构中,调用其执行 语句。
2.switch结构中的表达式,只能是如下六种数据类型:
byte ,short, char, int, 枚举类型, String类型
*/
class SwitchCaseTest{
public static void main(String[] args){
int number = 1;
switch(number){
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
default:
System.out.println("other");
}
}
}
例题1
//要求使用switch
class SwitchCaseTest1{
public static void main(String[] args){
int score = 78;
switch(score/10){
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("不及格");
case 6:
case 7:
case 8:
case 9:
case 10:
System.out.println("及格");
break;
/*switch(score/60){
case 0;
System.out.println("不及格");
case 1;
System.out.println("及格");
break;
}*/
}
}
}
例题2
说明:break在switch-case中是可选的
class SwitchCaseTest1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("请输入2019年的month:")
int month = scan.nextInt();
System.out.println("请输入2019年的day:")
int day = scan.nextInt();
switch(month){
case 12:
sumDays += 31;
case 11:
sumDays += 30;
case 10:
sumDays += 31;
case 9:
sumDays += 30;
case 8:
sumDays += 31;
case 7:
sumDays += 31;
case 6:
sumDays += 30;
case 5:
sumDays += 31;
case 4:
sumDays += 30;
case 3:
sumDays += 31;
case 2:
sumDays += 29;
case 1:
sumDays += day;
}
System.out.println("2019年"+month+"月"+day+"日是当年的第"+sumDays+"天");
}
}
说明:1.凡是可以使用switch-case的结构,都可以转换为if-slse。反之,不成立