【0 基础学 Java】 (五)分支和循环
【0 基础学 Java】 (五)分支和循环
码字不易,对你有帮助 点赞/转发/关注 支持一下作者
微信搜公众号:不会编程的程序圆
看更多干货,获取第一时间更新
想看更好的排版,可以阅读原文
点击阅读原文
思维导图
目录
@[toc]
正文
一 顺序结构
按照代码书写的顺序一行一行执行 。
System.out.println(1);
System.out.println(2);
System.out.println(3);
//运行结果
1
2
3
二 分支结构
1. if 语句
Ⅰ:单分支
if(布尔表达式){
//条件满足时执行代码
}
例1:布尔表达式的含义
int a = 10;
// C语言中,0是假,非0是真
// 但是在 Java 中,真只有 true,假只有 false
// 所以很明显,下面这样的写法是错误的
if(a){
System.out.println("真");
}
修改:
int a = 10;
// a != 0 是关系运算符,我们知道,关系运算符返回值类型是 boolean 类型
if(a != 0){
System.out.println("真");
}
Ⅱ:双分支
if(布尔表达式){
//条件满足时执行代码
}else{
//条件不满足时执行代码
}
Ⅲ:多分支
if(布尔表达式){
//条件满足时执行代码
}else if(布尔表达式){
//条件满足时执行代码
}else{
//条件都不满足时执行代码
}
Ⅳ:编码规范
例2:总写花括号是一种好习惯
请问下面的代码会输出什么?
int a = 10;
if(a == 10)
System.out.println("我应该稳了吧?");
System.out.println("我也想露个面~");
搜索下面的链接查看答案:
下面的代码又会输出什么呢?
int a = 10;
if(a == 10)
System.out.println("我应该稳了吧?");
System.out.println("我也想露个面~");
else
System.out.println("你们都别想了,赢家会是我!");
搜索下面的链接查看答案:
if 如果不带花括号,只会默认执行一条语句。
例3:else 与 if 匹配问题
int x = 10;
int y = 5;
if (x == 10)
if (y == 10)
System.out.println("就差一步!");
else
System.out.println("楼上真可怜~");
// 输出:
楼上真可怜~
int x = 5;
int y = 10;
if (x == 10)
if (y == 10)
System.out.println("就差一步!");
else
System.out.println("楼上真可怜~");
// 输出:
啥也不输出
else 是和最接近的 if 匹配。
但是实际开发中我们 不建议 这么写,最好加上大括号。
修改:
int x = 5;
int y = 10;
if (x == 10){
if (y == 10){
System.out.println("就差一步!");
}
}else{
System.out.println("楼上真可怜~");
}
例 4:代码风格
// 风格1
int x = 10;
if (x == 10) {
// 满足条件
} else {
// 不满足条件
}
// 风格2
int x = 10;
if (x == 10)
{
// 满足条件
}
else
{
// 不满足条件
}
虽然两种方式都是合法的,但是 Java 中更推荐使用风格1,{ 放在 if / else 同一行。
例 5 :分号问题
int x = 20;
if (x == 10); {
System.out.println("hehe");
}
// 运行结果
hehe
此处多写了一个 分号,导致分号成为了 if 语句的语句体,而 { } 中的代码已经成为了和一个 if 无关的代码块 。
Ⅴ:练习1
1) 判定一个数字是奇数还是偶数
import java.util.Scanner;// 1
public class helloWorld{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);//2
int n = scan.nextInt();//3
//以上1,2,3 三条语句不懂没关系,后面我们会讲,
//它们的目的类似C语言的 scanf 函数
if(n % 2 == 0){
System.out.println(n + " 是偶数");
}else{
System.out.println(n + " 是奇数");
}
}
}
2) 判断一个数的正负
import java.util.Scanner;
public class helloWorld{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
if(n < 0){
System.out.println(n + " 是负数");
}else if(n > 0){
System.out.println(n + " 是正数");
}else{
System.out.println(n + "既不是正数也不是负数");
}
}
}
3) 判断一年是否是闰年
import java.util.Scanner;
public class helloWorld{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
if(n < 0){
System.out.println("输入的年份不能小于 0 。");
}else if( ((n % 4 == 0) && (n % 100 == 0)) || (n % 400 == 0) ){
System.out.println(n + " 是闰年");
}else{
System.out.println(n + " 不是闰年");
}
}
}
这三个代码都很简单,建议自己写一遍,其实就是训练你熟练的写模板(lol)。
2. switch 语句
switch(整数|枚举|字符|字符串){
case 内容1 : {
内容满足时执行语句;
[break;]
}
case 内容2 : {
内容满足时执行语句;
[break;]
}
...
default:{
内容都不满足时执行语句;
[break;]
}
}
整型中:只有 byte,short,int 是合法的,不能使用 long 类型。
Ⅰ:注意事项
break 不要遗漏
例7 :
int day = 1;
switch(day) {
case 1:
System.out.println("星期一");
// break;
case 2:
System.out.println("星期二");
break;
}
// 运行结果
星期一
星期二
不写 break 的时候, case 语句会依次向下执行, 从而失去了多分支的效果 。
因此我们建议:没有特殊的要求,在每个 case 中都加上 break。
switch 中的值只能是 整数|枚举|字符|字符串
例8:
double num = 1.0;
switch(num) {
case 1.0:
System.out.println("hehe");
break;
case 2.0:
System.out.println("haha");
break;
}
// 编译出错
Test.java:4: 错误: 不兼容的类型: 从double转换到int可能会有损失
switch(num) {
^
1 个错误
switch 不能表达复杂的条件
// 例如:
// 这样的代码使用 if 很容易表达, 但是使用 switch 就无法表示.
if (num > 10 && num < 20) {
System.out.println("hehe");
}
switch 虽然支持嵌套,但是会很丑
int x = 1;
int y = 1;
switch(x) {
case 1:
switch(y) {
case 1:
System.out.println("hehe");
break;
}
break;
case 2:
System.out.println("haha");
break;
}
总结:
综上,我们发现,switch 的使用局限性是比较大的 。
三 循环结构
1. while 循环
while(循环条件){
循环语句;
}
循环条件为 true,则执行循环语句;否则结束循环 。
练习2
1) 打印 1 - 10 的数字
public class helloWorld{
public static void main(String[] args) {
int num = 1;
while(num <= 10){
System.out.println(num++);
}
}
}
2) 计算 1 - 100 的和
public class helloWorld{
public static void main(String[] args) {
int num = 1;
int sum = 0;
while(num <= 100){
sum += num;
++num;
}
System.out.println(sum);
}
}
变型:打印 100 ~ 200 内奇数的和 和 偶数的和
public class helloWorld{
public static void main(String[] args) {
int n = 100;
int sumEven = 0;
while(n <= 200){
sumEven += n;
n += 2;
}
n = 101;
int sumOdd = 0;
while(n <= 200){
sumOdd += n;
n += 2;
}
System.out.println("偶数的和为:" + sumEven);
System.out.println("奇数的和为:" + sumOdd);
}
}
重构变型
public class helloWorld{
public static void main(String[] args) {
int lower = 100;
int upper = 200;
int n = lower;
byte flag = 1;
int sumEven = 0, sumOdd = 0;
//判断第一个数是奇数还是偶数
if(lower % 2 == 0){
flag = 1;
}else{
flag = -1;
}
while(n <= upper){
if(flag == 1){
sumEven += n;
}else{
sumOdd += n;
}
flag *= -1;
++n;
}
System.out.println("偶数的和为:" + sumEven);
System.out.println("奇数的和为:" + sumOdd);
}
}
3) 计算 5 的阶乘
public class helloWorld{
public static void main(String[] args) {
int n = 5;
int sum = 1;
while(n > 0){
sum *= n;
--n;
}
System.out.println(sum);
}
}
4) 计算 1! + 2! + 3! + 4! + 5!
public class helloWorld{
public static void main(String[] args) {
int target = 5;
int n = 1;
int sum = 0;
int next = 1;
while(n <= target){
sum += next;
next *= n + 1;// 下一个阶乘 等于 当前阶乘 * 下一个数
++n;
}
System.out.println(sum);
}
}
注意
- 和 if 类似,while 下面的语句可以不写 { } ,但是不写的时候只能支持一条语句。建议还是加上 { } 。
- 和 if 类似,while 后面的 { 建议和 while 写在同一行 。
- 和 if 类似,while 后面不要多写 分号,否则可能导致循环不能正确执行 。
int num = 1;
while (num <= 10); {
System.out.println(num);
num++;
}
// 执行结果
[无任何输出, 程序死循环]
此时,为 while 的语句体(这是一个空语句),实际的 { } 部分和循环无关。此时循环条件 num <= 10 恒成立,导致代码死循环了。
2. break 关键字
break 的功能是让循环提前结束。
练习3
找到 100 - 200 中第一个 3 的倍数
public class helloWorld{
public static void main(String[] args) {
int upper = 200;
int lower = 100;
int n = 100;
while(n >= lower && n <= upper){
if(n % 3 == 0){
break;
}
++n;
}
System.out.println(n);
}
}
3. continue 关键字
continue 的功能是跳过这次循环,立即进入下次循环。
练习4
输出 1 ~ 10 之间的奇数
public class helloWorld{
public static void main(String[] args) {
int n = 1;
while(n >= 1 && n <= 10){
if(n % 2 == 0){
n++;
continue;
}
System.out.println(n++);
}
}
}
4. for 循环
for(表达式1;表达式2;表达式3){
循环体;
}
表达式 1:用于初始化循环变量
表达式 2:循环条件
表达式 3:更新循环变量
练习5:
1) 打印 1 - 10 的数字
public class helloWorld{
public static void main(String[] args) {
int i;
int lower = 1;
int upper = 10;
for(i = lower; i <= upper; i++){
System.out.println(i);
}
}
}
2) 计算 1 - 100 的和
public class helloWorld{
public static void main(String[] args) {
int i;
int sum = 0;
int lower = 1;
int upper = 100;
for(i = lower; i <= upper; i++){
sum += i;
}
System.out.println(sum);
}
}
3) 计算 5 的阶乘
public class helloWorld{
public static void main(String[] args) {
int target = 5;
int i;
int sum = 1;
for(i = 1; i <= target; i++){
sum *= i;
}
System.out.println(sum);
}
}
4) 计算 1! + 2! + 3! + 4! + 5!
public class helloWorld{
public static void main(String[] args) {
int target = 5;
int i;
int sum = 0;
int next = 1;
for(i = 1; i <= target; i++){
next *= i;
sum += next;
}
System.out.println(sum);
}
}
注意
与 while 相同
5. do while 循环(选学)
do{
循环语句;
}while(循环条件);
先执行循环语句,再判定循环条件 。
例6:打印 1 ~ 10
public class helloWorld{
public static void main(String[] args) {
int lower = 1;
int upper = 10;
int i = lower;
do{
System.out.println(i);
i++;
}while(i <= upper);//不要忘记分号
}
}
注意
- do while 循环最后的分号不要忘记
- 一般 do while 很少用到, 更推荐使用 for 和 while.
四 输入输出
1. 输出到控制台
基本语法
System.out.println(msg); // 输出一个字符串, 带换行
System.out.print(msg); // 输出一个字符串, 不带换行
System.out.printf(format, msg); // 格式化输出
转换说明
与 C 基本相同。C 语言的转换说明在我的C语言教学 【C语言入门到精通】系列对应文章中讲过,想系统的了解可以去看看。
2. 从键盘输入
Ⅰ:读一个字符(选学)
import java.io.IOException; // 需要导入 IOException 包
try {
System.out.print("Enter a Char:");
char i = (char) System.in.read();
System.out.println("your char is :"+i);
} catch (IOException e) {
System.out.println("exception");
}
这种方式比较麻烦, 我们不推荐使用
Ⅱ 使用 Scanner 读取 字符串/整数/浮点数
import java.util.Scanner;
public class helloWorld{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的姓名:");
String name = sc.nextLine();
System.out.println("请输入你的年龄:");
int age = sc.nextInt();
System.out.println("请输入你的工资:");
float salary = sc.nextFloat();
System.out.println("你的信息如下:");
System.out.println("姓名:" + name + " 年龄:" + age + " 工资:" + salary);
sc.close();// 注意调用关闭方法
}
}
Ⅲ:使用 Scanner 循环读取 N 个数字
Scanner sc = new Scanner(System.in);
double sum = 0.0;
int num = 0;
while (sc.hasNextDouble()) {
double tmp = sc.nextDouble();
sum += tmp;
num++;
}
System.out.println("sum = " + sum);
System.out.println("avg = " + sum / num);
sc.close();
如何结束输入
注意事项:当循环输入多个数据的时候,使用 ctrl + z 来结束输入 (Windows 上使用 ctrl + z, Linux / Mac 上使用 ctrl + d) 。
[0 基础学 java ] 系列的代码可以在我的 Github 仓库查看,地址如下:
https://github.com/hairrrrr/Java_SE_EnjoyLearning
欢迎 star !(点一个 star 方便你下回查看)
本系列的教学也可以在 GitHub 观看(GitHub 上看教学的好处是所有文章的目录比较清晰)。
以上就是本次的内容。
如果文章有错误欢迎指正和补充,感谢!
最后,如果你还有什么问题或者想知道到的,可以在评论区告诉我呦,我可以在后面的文章加上你们的真知灼见。
关注我,看更多干货!
我是程序圆,我们下次再见。