顺序结构
程序默认流程(从上至下)
分支结构
if分支
根据判定的结果(真或假)决定执行某个分支的代码。
if的三种格式
switch分支
也是匹配条件去执行,适合做值匹配的分支选择,结构清晰,格式良好。
格式
执行流程
1. 先执行表达式中的值,然后与case后的值进行匹配。
2. 匹配那个case值为true就去执行哪个case,直到遇到break后跳出switch分支。
3. 如果case值都没匹配上,就执行default代码。
注意
1. switch分支表达式只能是byte、short、int、char,JDK5开始支持枚举,JDK7开始支持String,不支持double、float、long(不精确)。
2. case给出的值不能重复,且只能是字面量,不能是变量。
3. 记得一定要加break,否则会出现穿透现象。
循环结构
for循环
控制一段代码反复执行。
格式
案例1
求1-5之间的数据和,并把结果在控制台输出
//求1-5之间的数据和,并把结果在控制台输出
public class test {
public static void main(String[] args) {
int sum = 0;
for(int i = 1;i <= 5;i++){
sum += i;
}
System.out.println("1-5和为"+sum);
}
}
案例2
求1-10之间的奇数和,并将结果在控制台上输出
//求1-10之间的奇数和,并将结果在控制台上输出
public class test {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i+=2) {
sum += i;
}
System.out.println("1-10奇数和为"+sum);
}
}
案例3
求水仙花数
1. 水仙花数是一个三位数
1. 水仙花数的个位、十位、百位数字立方和等于原数
/*
求水仙花数
1. 水仙花数是一个三位数
1. 水仙花数的个位、十位、百位数字立方和等于原数
*/
public class test {
public static void main(String[] args) {
int ge;
int shi;
int bai;
int sum = 0;
for (int i = 100; i <= 999; i++) {
ge = i % 10; //获取个位
shi = i / 10 % 10; //获取十位
bai = i /100;//获取百位
sum = (ge * ge * ge)+(shi * shi * shi)+(bai * bai * bai);
if(sum == i){
System.out.println(sum + "是水仙花数");
}
}
}
}
while循环
格式
什么时候用for循环?什么时候用while循环?
因为for、while功能上完全一样,所以使用的规范是:知道有多少次循环用for,不知道则用while。
案例
珠穆朗玛峰案例:
珠穆朗玛峰(8848.86米 = 8848860毫米),假设有一张足够大的纸,厚度为0.1毫米。问:折叠多少次,可以折成珠穆朗玛峰的高度
//珠穆朗玛峰案例
public class test {
public static void main(String[] args) {
double high = 0.1; //纸张高度
int i = 0; //次数
while(high < 8848860)
{
high *= 2.0;
i++;
}
System.out.println("共叠了" + i + "次");
System.out.println("纸张厚度为" + high);//第二十七次数据溢出了
}
}
do-while循环
先执行再判断循环条件。(一定会执行至少一次)
格式
死循环
一直循环执行下去,没有干预就 不会停下来。
格式
案例
密码验证
系统密码是520,用户不断输入密码验证,验证不对输出密码错误,正确则输出欢迎进入系统,并停止程序
//密码验证
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int pw;
while (true)
{
System.out.println("请输入系统密码:");
pw = sc.nextInt();
if(pw == 520){
System.out.println("欢迎进入系统");
break;
}
else{
System.out.println("密码错误");
}
}
}
}
循环嵌套
指的是循环中又包含循环
特点:外部循环执行完一次,内部循环全部执行完一次。
案例
在控制台使用*打印出4行五列矩阵
//在控制台使用*打印出4行五列矩阵
public class test {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
跳转关键字
break
跳出,并结束当前所处的循环体。
continue
跳出当前循环的当次执行,进入下一次循环。
案例技术:随机数Random类
Random使用
案例
猜数字游戏
随机生成一个1-100之间的数据,提示用户猜测,猜大提示过大,猜小提示过小,直到猜中结束游戏。
//猜数字游戏
public class test {
public static void main(String[] args) {
int data;
int input;
Random r = new Random();
Scanner sc = new Scanner(System.in);
data = r.nextInt(100) + 1;
while (true)
{
System.out.println("请输入猜测数字");
input = sc.nextInt();
if (input == data){
System.out.println("猜对了");
break;
}
else if(input > data)
System.out.println("过大");
else if(input < data)
System.out.println("过小");
}
}
}