流程控制语句
通过一些语句,控制程序的执行流程。
1.顺序结构
顺序结构语句是Java程序默认的执行流程,按照代码的先后顺序,从上到下依次执行。
2.分支结构
(1) if
1)if的第一种格式(单条件判断)
if (关系表达式) {
语句体;
}
Ⅰ.首先计算关系表达式的值
Ⅱ.如果关系表达式的值为true就执行语句体
Ⅲ.如果关系表达式的值为false就不执行语句体
Ⅳ.继续执行后面的其他语句
①大括号的左半边写在if那一行的末尾
②在语句体中,如果只有一句代码大括号可以省略不写但建议还是写
public class BranchStructure{
public static void main(String[] args){
int number = 20;
if(number >= 10)
int a = 10;//会报错,因为这一句包含两个语句:定义变量a和给a赋值,要加大括号
}
}
③如果对一个布尔类型的变量进行判断,不要用==号,直接把变量写在小括号即可
2)if的第二种格式(双条件判断)
if (关系表达式) {
语句体1;
} else {
语句体2;
}
Ⅰ.首先计算关系表达式的值
Ⅱ.如果关系表达式的值为true就执行语句体1
Ⅲ.如果关系表达式的值为false就执行语句体2
Ⅳ.继续执行后面的其他语句
商品付款
假设,用户在超市实际购买,商品总价为:600元。
键盘录入一个整数表示用户实际支付的钱。
如果付款大于等于600,表示付款成功。否则付款失败。
import java.util.Scanner;
public class PayMoney{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the quantity you paid");
int money = sc.nextInt();
if(money >= 600){
System.out.println("Pay successfully!");
} else {
System.out.println("Pay failedly!");
}
}
}
影院选座
假设某影院售卖了100张票,票的序号为1~100.
其中奇数票号坐左侧,偶数票号坐右侧。
键盘录入一个整数表示电影票的票号。
根据不同情况,给出不同的提示:
如果票号为奇数,那么打印坐左边
如果票号为偶数,那么打印坐右边。
import java.util.Scanner;
public class CinemaSeatSelect{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your ticket number");
int ticket = sc.nextInt();
if(ticket >1 && seat <=100){
if(ticket % 2 == 1) {//if的嵌套
System.out.println("You sit on the left side.");
} else {
System.out.println("You sit on the right side.");
}
} else {
System.out.println("Ticket number is invalid!");
}
}
}
3)if的第三种格式(多条件判断)
if(关系表达式){
语句体1;
} else if(关系表达式2) {
语句体2;
}
…
else{
语句体n+1;
}
Ⅰ.首先计算关系表达式1的值
Ⅱ.如果为true就执行语句体1;如果为false就计算关系表达式2的值
Ⅲ.如果为true就执行语句体2;如果为false就计算关系表达式3的值
Ⅳ…
Ⅴ.如果所有关系表达式结果都为false,就执行语句体n+1。
总结成一句话:
从上往下依次进行判断
只要有一个判断为真,就执行对应的语句体
如果所有的判断都为假,就执行else的语句体
小明的礼物
95~100分:自行车一辆
90~94分:游乐场玩一天
80~89分:变形金刚一个
80分以下:被挨打
import java.util.Scanner;
public class ScoreGift{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your score");
int score = sc.nextInt();
if(score >=0 && score <=100){
if(score >=95 && score <=100){
System.out.println("You will get a bicycle!");
} else if(score >=90 && score <=94){
System.out.println("You can play at the amusement park for a day!");
} else if(score >= 80 && score <=89){
System.out.println("You will get a transformer!");
} else {
System.out.println("You will be beaten!");
}
} else {
System.out.println("Your score is invalid!");
}
}
}
商品的价格
商场都会有VIP的会员制,根据不同的会员会有不同的折扣。
假设商品总价为1000。
键盘录入会员级别,并计算出实际支付的钱。
会员1级:打9折。
会员2级:打8折。
会员3级:打7折。
非会员:不打折。
import java.util.Scanner;
public class GoodPrice{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your vipLevel(If you are not vip,please enter 0)");//提示语句要写在int vipLevel = sc.nextInt();语句的上面
int vipLevel = sc.nextInt();
double price = 1000;//price乘了0.9/0.8/0.7,所以用double
if(vipLevel >= 0&& vipLevel <= 3) {
if(vipLevel == 1){
price = price*0.9;
System.out.println("There is 10% discount on product price.");
} else if(vipLevel == 2){
price *= 0.8;
System.out.println("There is 20% discount on product price.");
} else if(vipLevel == 3){
price *= 0.7;
System.out.println("There is 30% discount on product price.");
} else{
System.out.println("There is no discount.");
}
System.out.println("The amount you need to pay is"+price+"$");
} else{
System.out.println("Your vipLevel is invalid!");
}
}
}
(2)switch
1)格式
switch(表达式) {
case 值1://case和值之间有空格!
语句体1;
break;
case 值2:
语句体2;
break;
…
default:
语句体n+1;
break;
}
Ⅰ.首先计算表达式的值。
Ⅱ.依次和case后面的值进行比较,如果有对应的值,就会执行相应的语句,在执行的过程中,遇到break就会结束。
Ⅲ.如果所有的case后面的值和表达式的值都不匹配,就会执行default里面的语句体,然后结束整个switch语句。
2)格式说明
Ⅰ.表达式:(将要匹配的值)取值为byte、short、int、char。JDK5以后可以是枚举,JDK7以后可以是String。
Ⅱ.case:后面跟的是要和表达式进行比较的值(被匹配的值)。
Ⅲ.break:表示中断、结束的意思,用来结束switch语句。
Ⅳ.default:表示所有情况都不匹配的时候,就执行该处的内容,和if语句的else相似。
Ⅴ.case后面的值只能是字面量,不能是变量。
Ⅵ.case给出的值不允许重复。
运动计划
键盘录入星期数,显示今天的减肥活动。
周一:跑步
周二:游泳
周三:慢走
周四:动感单车
周五:拳击
周六:爬山
周日:好好吃一顿
import java.util.Scanner;
public class SportSchedule{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter today's day of the week.");
int today = sc.nextInt();
switch(today){
case 1:
System.out.println("Run");
break;
case 2:
System.out.println("Swim");
break;
case 3:
System.out.println("Walk slowly");
break;
case 4:
System.out.println("Dynamic bicycle");
break;
case 5:
System.out.println("Boxing");
break;
case 6:
System.out.println("Climb mountain");
break;
case 7:
System.out.println("Have a good meal.");
break;
default:
System.out.println("Your input is invalid!");
break;
}
}
}
3)default的位置和省略
①位置
default不一定是写在最下面,我们可以写在任意位置,只不过习惯写在最下面。
②省略
default可以省略,语法不会有问题,但是不建议省略。
4)case穿透
break省略了就会导致case穿透:
没有break,那么程序会继续执行下一个case的语句体,一直遇到break或者大括号为止。
休息日和工作日
如果多个case的语句体重复了,那么我们考虑利用case穿透去简化代码。
键盘录入星期数,输出工作日,休息日。
(1~5)工作日,(6~7)休息日。
import java.util.Scanner;
public class RestOrWork{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter today's day of the weak.");
int today = sc.nextInt();
switch(today){
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weakday");
break;
case 6:
case 7:
System.out.println("Rest day");
break;
default:
System.out.println("Your input is invalid!");
break;
}
}
}
or
import java.util.Scanner;
public class RestOrWork{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter today's day of the weak.");
int today = sc.nextInt();
switch(today){
case 1,2,3,4,5:
System.out.println("Weakday");
break;
case 6,7:
System.out.println("Rest day");
break;
default:
System.out.println("Your input is invalid!");
break;
}
}
}
or
import java.util.Scanner;
public class RestOrWork{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter today's day of the weak.");
int today = sc.nextInt();
switch(today){
case 1,2,3,4,5 -> System.out.println("Weakday");
case 6,7 -> System.out.println("Rest day");
default -> System.out.println("Your input is invalid!");
}
}
}
5)switch新特性(JDK12)
switch(表达式) {
case 值1 -> {//不用再写break;
语句体1;//语句体只有一句,大括号可以省略
}
case 值2 -> {
语句体2;
}
…
default -> {
语句体n+1;
}
}
6)switch和if第三种格式各自的使用场景
if的第三种格式,一般用于对范围的判断
switch,把有限个数据一一列举出来,让我们任选其一`
3.循环结构
(1)for
for(初始化语句;条件判断语句;条件控制语句){
循环体语句;
}
①执行初始化语句
②执行条件判断语句,看其结果是true还是false
如果是false,循环结束
如果是true,执行循环体语句
③执行条件控制语句
④回到②继续执行条件判断语句
总结:
初始化语句只执行一次
判断语句为true,循环继续
判断语句为false,循环结束
打印5~1
public class Reverse{
public static void main(String[] args){
for(int i = 5 ; i >= 1 ; i--){
System.out.println(i);
}
}
}
求和(求1~5之间的和)
public class Sum1{
public static void main(String[] args){
int sum=0;
/*1.求和的变量不能定义在循环的里面,因为变量只在所属的大括号中有效
2.如果我们把变量定义在循环的里面,那么变量只能在本次循环有效。当本次循环结束之后,变量就会从内存中消失。第二次循环开始时,又回重新定义一个新的变量。
*/
for(int i = 1;i <= 5;i++){
sum += i;
}
System.out.println(sum);
}
}
求和(求1~100之间的偶数和)
public class Sum2{
public static void main(String[] args){
int sum = 0;
for( int i = 2;i <= 100;i += 2){//快速生产for循环:100.fori+回车
sum += i;
}
System.out.println(sum);
}
}
or
public class Sum3{
public static void main(String[] args){
int sum = 0;
for( int i = 1;i <= 100;i ++){//快速生产for循环:100.fori+回车
if(i % 2 == 0){
sum += i;
}
}
System.out.println(sum);
}
}
统计满足条件的数字
键盘录入两个数字,表示一个范围。
统计这个范围中
既能被3整除,又能被5整除的数字有多少个?
import java.util.Scanner;
public class Count{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the lower bound of the range.");
int lowerBound = sc.nextInt();
System.out.println("Please enter the upper bound of the range.");
int upperBound = sc.nextInt();
int count = 0;
for(int i = lowerBound;i <= upperBound;i++){
if(i % 3 == 0 && i % 5 == 0){
count++;
}
}
System.out.println("There are/is "+ count +" integer(s) you need in your range.");
}
}
(2)while
初始化语句;
while(条件判断语句){
循环体语句;
条件控制语句;
}
和for循环一样:
初始化语句只执行一次
判断条件为true,循环继续
判断条件为false,循环结束
for和while的对比
for循环中,控制循环的变量,因为归属for循环的语法结构,在for循环结束后,就不能再次被访问到了。
while循环中,控制循环的变量,对于while循环来说不归属其语法结构中,在while循环结束后,该变量还可以继续使用。
初始化语句;
for(;条件判断语句;条件控制语句){
循环体语句;
}
for循环中:知到循环次数或者循环的范围
while循环:不知道循环的次数和范围,只知道循环的结束条件
打印折纸的次数
世界最高山峰是珠穆朗玛峰(8844.43米=8844430毫米),假如我有一张足够大的纸,它的厚度是0.1毫米。
请问,我折叠多少次,可以折成珠穆朗玛峰的高度?
public class FoldPaper{
public static void main(String[] args){
double mountHeight = 8844430;
double paper = 0.1;
int count = 0;
while(paper < mountHeight){
paper *= 2;
count++;
}
System.out.println("You have folded " + count +" times in total.");
}
}
回文数(递归)
给你一个整数x。
如果x是一个回文整数,打印true;否则,打印false。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如:121是回文,而123不是。
import java.util.Scanner;
public class Palindrome{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a integer.");
int number = sc.nextInt();
int tmp = number;
int result = 0;
while(number > 0){
int senior = number % 10;
number /= 10;
result = result * 10 + senior;
}
if(result == tmp){//注意number一直在变
System.out.println("True");
} else {
System.out.println("False");
}
}
}
求商和余数
给定两个整数,被除数和除数(都是正数,且不超过int的范围)。
将两数相除,要求不使用乘法、除法和%运算符。
得到商和余数。
import java.util.Scanner;
public class Divide{
public static void main(String[] arga){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the divident.");
int divident = sc.nextInt();
System.out.println("Please enter the divisor.");
int divisor = sc.nextInt();
int count = 0;
while(divident >= divisor){
divident -= divisor;
count++;
}
System.out.println("The quotient is " + count);
System.out.println("The remainder is " + divident);
}
}
(3)do…while
1)格式
初始化语句;
do{
循环体语句;
条件控制语句;
}while(条件判断语句);
总结:
先执行后判断