Java基础语法(三)
文章目录
流程控制
if分支的三种形式

例如:
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的温度");
double temperature = sc.nextDouble();
if (temperature > 38.0) {
System.out.println("您可能要嘎了");
} else if(temperature > 37.0) {
System.out.println("您可能需要住院了");
} else if (temperature > 36.0){
System.out.println("您可能需要吃药");
} else {
System.out.println("啥事没有,玩去吧");
}switch语法格式

例如:
Scanner sc = new Scanner(System.in);
System.out.println("请告诉我今天是周几?");
String day = sc.next();
switch (day) {
case "周一":
System.out.println("埋头苦干");
break;
case "周二":
System.out.println("请求帮忙");
break;
case "周三":
System.out.println("啤酒小龙虾");
break;
case "周四":
System.out.println("帮助女同学");
break;
case "周五":
System.out.println("大吉大利,今晚吃鸡");
break;
case "周六":
System.out.println("相亲");
break;
case "周日":
System.out.println("郁郁寡欢,准备上班");
break;
default:
System.out.println("大哥,你连周几都能搞错...");
}
循环结构
for循环

例如:
// for循环求和
int sum = 0;
for(int i = 0; i <= 100; i++) {
sum += i;
}
System.out.println(sum); // 5050例如:
// 100以内奇数和
int sum = 0;
for(int i = 0; i <= 100; i++) {
if (i % 2 != 0) {
sum += i;
}
}
System.out.println(sum); // 2500while循环

例如:
// while循环
int i = 0;
while( i < 10 ) {
System.out.println(i);
i++;
}练习:

// 折纸 --> 珠峰 高度
double zfHeight = 8848860;
double paperHeight = 0.1;
int count = 0;
while(paperHeight < zfHeight) {
paperHeight = paperHeight * 2; // 每次折纸都会高度翻倍
count++;
}
System.out.println(paperHeight); // 1.34217728E7
System.out.println(count); // 27do...while循环

do...while循环会在判断之前先执行一次。
死循环
可以一直执行下去,没有干预不会停止的循环。
常见的死循环的写法:

break和continue

练习
猜数字:
// 弄出一个随机数,让用户去猜
Random num = new Random();
int n = num.nextInt(6) + 10; // 10 - 15
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("请输入猜测的数字:");
int guessNum = sc.nextInt();
if (guessNum == n) {
System.out.println("猜对了");
break;
} else {
System.out.println("猜错了");
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论