Java基础–分支结构
If语句
- if 语句
if(表达式) {
语句体;
}
- if else语句
if(表达式){
语句体1;
}
else{
语句体2;
}
3.if…else if …else
if(关系表达式1){
语句体1;
}
else if(关系表达式2){
语句体2;
}
…
else{
语句体n+1;
}
/*分支结构
* 1. if结构
if(表达式) {
语句体;
}
------------
2. if else语句
if(表达式){
语句体1;
}
else{
语句体2;
}
---------------
3.if…else if …else
if(关系表达式1){
语句体1;
}
else if(关系表达式2){
语句体2;
}
…
else{
语句体n+1;
}
*/
import java.util.*;
public class IfDemo {
public static void main(String[] args) {
/* //练习分支语句if
int a = 10;
int b = 20;
b = 15;
if(a>b) {
System.out.println("a大于b");
}
else {
System.out.println("a小于b");
}
System.out.println("结束");
*/
/*练习if…else语句
* System.out.println("请输入一个整数:");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
if(i%2 == 0) {
System.out.println("该数为偶数!");
}
else {
System.out.println("该数为奇数!");
}
*/
/*
//练习if… else if …else语句
System.out.println("请输入一个星期数(1-7):");
Scanner sc = new Scanner(System.in);
int week = sc.nextInt();
if(week == 1) {
System.out.println("今天星期一");
}
else if(week == 2) {
System.out.println("今天星期二");
}
else if(week == 3) {
System.out.println("今天星期三");
}
else if(week == 4) {
System.out.println("今天星期四");
}
else if(week == 5) {
System.out.println("今天星期五");
}
else {
System.out.println("今天周末,不上班!");
}
*/
System.out.println("请输入小明的成绩:");//给出提示语
Scanner sc = new Scanner(System.in);//创建对象
Double score = sc. nextDouble();//输入数据
if(score >=95) {
System.out.println("奖励一辆自行车!");
}
else if(score >=90) {
System.out.println("奖励去游乐园玩!");
}
else if(score >=80) {
System.out.println("奖励一个变形金刚!");
}
else {
System.out.println("胖揍一顿!");
}
}
}
运行截图如下:
=================================
switch 语句
switch(表达式){
case1:
语句体1;
break;
case2:
语句体2;
break;
…
default:
语句体n+1;
[break;]
}
// Switch语句结构
/*
*
switch(表达式){
case1:
语句体1;
break;
case2:
语句体2;
break;
……
default:
语句体n+1;
[break;]
}
*/
import java.util.*;
public class SwitchDemo {
public static void main(String[] args) {
/*
System.out.println("请输入一个星期数(1-7):");
Scanner sc = new Scanner(System.in);
int week = sc.nextInt();
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("您输入的星期数有误!");
}
*/
//case 穿透现象
System.out.println("请输入一个月份:");
Scanner sc = new Scanner(System.in);
int mouth = sc.nextInt();
switch(mouth) {
case 1:
case 2:
case 12:
System.out.println("该月份为冬季!");
break;
case 3:
case 4:
case 5:
System.out.println("该月份为春季!");
break;
case 6:
case 7:
case 8:
System.out.println("该月份为夏季!");
break;
case 9:
case 10:
case 11:
System.out.println("该月份为秋季");
break;
default:
System.out.println("您所输入的月份不合法!");
}
}
}
运行截图如下: