Java流程控制

Java流程控制

用户交互Scanner

我们之前学习的基本语法中我们并没有实现程序和人的交互,但是Java给我们提供了这样一个工具类,我们可以获取用户的输入。java.util.Scanner 是 Java5 的新特性,我们可以通过 Scanner 类来获取用户的输入

基础语法:

Scanner scanner = new Scanner(System.in);

通过Scanner 类的 next() 与 nextLine() 方法获取输入的字符串,在读取前我们一般需要 使用 hasNext() 与 hasNextLine() 判断是否还有输入的数据。

接收字符

  • next()方法:

    1. 一定要读取到有效字符后才可以结束输入

    2. 对输入有效字符串之前遇到的空白,next() 方法会自动将其去掉

    3. 只有输入有效字符之后才将其后面输入的空白作为分隔符或结束符

    4. next() 不能得到带有空格的字符串

      import java.util.Scanner;
      
      public class Demo01 {
          public static void main(String[] args) {
              // 创建一个扫描对象,用于接收键盘数据
              Scanner scanner = new Scanner(System.in);
              System.out.print("使用next()方法接收:");
              // 判断用户有没有输入字符串
              if (scanner.hasNext()) {
                  // 接收用户的输入
                  String str = scanner.next(); // 程序会等待用户输入完毕再执行
                  System.out.println("输入的内容为:" + str); // 输入:Hello World 输出:Hello
              }
              // 凡是属于 IO 流的类如果不关闭会一直占用资源,要养成良好的习惯,用完就关闭
              scanner.close();
          }
      }
      
  • nextLine()方法:

    1. 以Enter作为结束符,也就是说 nextLine() 方法返回的是输入回车之前的所有字符‘

    2. 可以获得空白

      import java.util.Scanner;
      
      public class Demo02 {
          public static void main(String[] args) {
              // 从键盘接收数据
              Scanner scanner = new Scanner(System.in);
              System.out.print("使用nextLine()方法接收:");
              //判定是否还有输入
              if (scanner.hasNextLine()) {
                  String str = scanner.nextLine();
                  System.out.println("输入的内容为:" + str); // Hello World
              }
              scanner.close();
          }
      }
      

常用格式:

import java.util.Scanner;

public class Demo03 {
    public static void main(String[] args) {
        // 从键盘接收数据
        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入数据:");

        String str = scanner.nextLine(); // 接收一行数据

        System.out.println("输入的内容为:" + str);

        scanner.close(); // 关闭 IO 流
    }
}

接收其他数据类型

除了 hasNext() 方法之外,还有 hasNextInt()、hasNextDouble()、……

当然 next() 方法之外 ,还有 nextInt()、nextDouble()、……

import java.util.Scanner;

public class Demo04 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 从键盘接收数据
        int i = 0;
        float f = 0.0f;
        // 接收整数:
        System.out.print("请输入整数:");
        if (scanner.hasNextInt()) {
            i = scanner.nextInt();
            System.out.println("整数数据:" + i);
        } else {
            System.out.println("您输入的数据不是整数!");
        }
        // 接收小数:
        System.out.print("请输入小数:");
        if (scanner.hasNextFloat()) {
            f = scanner.nextFloat();
            System.out.println("小数数据:" + f);
        } else {
            System.out.println("您输入的数据不是小数!");
        }
        scanner.close();
    }
}

练习

我们可以输入多个数字,并求出其总和与平均数,每输入一个数字用回车确认。
通过输入非数字来结束输入并输出执行结果

import java.util.Scanner;

public class Demo05 {
    public static void main(String[] args) {
        // 接收键盘录入
        Scanner scanner = new Scanner(System.in);
        // 记录总和
        double sum = 0;
        // 记录输入的次数
        int m = 0;
        //循环输入
        while (scanner.hasNextDouble()) {
            // 输入一次,sum就加上输入的数
            sum += scanner.nextDouble();
            // 记录数自增1
            m++;
            System.out.println("第" + m + "次输入,当前和为:" + sum);
        }
        System.out.println("一共输入了:" + m + "次");
        System.out.println("和为:" + sum);
        System.out.println("平均数是:" + (sum / m));
        // 关闭 IO 流
        scanner.close();
    }
}

顺序结构

Java的基本结构就是顺序结构,除非特别指明,否则就按照一句一句从上往下依次执行。

顺序结构是最简单的算法结构

语句与语句之间,框与框之间是按从上到下的顺序进行,它是由若干个依次执行的处理步骤组成的

它是一个任何算法都离不开的一种基本算法结构

public class OrderDemo {
    public static void main(String[] args) {
        System.out.println("Hello1");
        System.out.println("Hello2");
        System.out.println("Hello3");
        System.out.println("Hello4");
        System.out.println("Hello5");
        // 从Hello1 依次执行到 Hello5
    }
}

选择结构

if单选择结构

我们很多时候需要去判断一个东西是否可行,然后我们才去执行,这样一个过程在持续中用if语句来表示

语法:

if (布尔表达式) {
    // 如果布尔表达式为true将执行的语句
}

代码:

public class IfDemo01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入一个内容:");
        String s = scanner.nextLine();
        // equals: 判断字符串是否一致
        if ("hello".equals(s)){
            // 如果输入的字符串是hello,就执行下面的语句
            System.out.println(s);
        }
        System.out.println("End");
        scanner.close();
    }
}

if双选择结构

那现在有个需求,考试分数大于60分及格,小于60分就不及格。这样的需求用一个if就搞不定了,我们需要有两个判断,需要一个双选择结构,所以就有了if-else结构。

语法:

if (布尔表达式) {
    // 如果布尔表达式的值为true
} else {
    // 如果布尔表达式的值为false
}

代码:

public class IfDemo02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入成绩:");
        double score = scanner.nextDouble();
        if (score >= 60) {
            System.out.println("成绩及格");
        } else {
            System.out.println("成绩不及格");
        }
        scanner.close();
    }
}

if多选择结构

我们发现刚才的代码不符合实际情况,真实的情况还可能存在ABCD,存在区间多级判断。比如90-100就是A,80-90 就是B……等等,在生活中我们很多时候的选择也不仅仅只有两个,所以我们需要一个多选择结构来处理这类问题!

if 语句至少有 1 个 else 语句,else 语句必须在所有的 else if 语句之后

if 语句可以有若干个 else if 语句,它们在 else 语句之前

一旦其中一个 else if 语句检测为 true,其他的 else if 以及 else 语句都将跳过执行

语法:

if (布尔表达式1) {
    // 如果布尔表达式1的值为true执行代码
} else if (布尔表达式2) {
    // 如果布尔表达式2的值为true执行代码
} else if (布尔表达式3) {
    // 如果布尔表达式3的值为true执行代码
} else {
    // 如果以上布尔表达式的值都不为true执行代码
}

代码:

public class IfDemo03 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入成绩:");
        double score = scanner.nextDouble();
        if (score == 100) {
            System.out.println("S");
        } else if (score < 100 && score >= 90) {
            System.out.println("A级");
        } else if (score < 90 && score >= 80) {
            System.out.println("B级");
        } else if (score < 80 && score >= 70) {
            System.out.println("C级");
        } else if (score < 70 && score >= 60) {
            System.out.println("D级");
        } else if (score >= 0 && score < 60) {
            System.out.println("不及格");
        } else {
            System.out.println("成绩不合法");
        }
        scanner.close();
    }
}

嵌套的if结构

使用嵌套的if...else语句是合法的。也就是说你可以在另一个if或者else if语句中使用if或者else if 语句。你可以像if语句一样嵌套else if...else。

语法:

if (布尔表达式1) {
    // 如果布尔表达式1的值为true执行代码
    if (布尔表达式2) { 
        // 如果布尔表达式2的值为true执行代码
	}
}

switch多选择结构

多选择结构还有一个实现方式就是switch case语句。

switch case语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。

语法:

switch(expression){
    case value:
        // 语句
        break; // 可选
    case value:
		// 语句
		break; // 可选
    // 你可以有任意数量的case语句
    default : // 可选
        // 语句
        break;
}

switch 语句中的变量类型可以是:

  • byte、short、int 或者 char
  • 从Java SE 7 开始
  • switch 支持字符串 String 类型了
  • 同时 case 标签必须为字符串常量或字面量

代码:

public class SwitchDemo01 {
    public static void main(String[] args) {
        char grade = 'C';
        // switch 匹配一个具体的值
        switch (grade) {
            case 'A':
                System.out.println("优秀");
                break; // 可选
            // case 穿透 执行完一个case,如果没有break,就会继续执行下一条 case 或 break
            case 'B':
                System.out.println("良好");
            case 'C':
                System.out.println("及格");
            case 'D':
                System.out.println("再接再厉");
                break;
            case 'E':
                System.out.println("挂科");
            default:
                System.out.println("未知等级");
                break;
        }
    }
}

反编译

Java文件:

package com.jh.struct;

public class SwitchDemo02 {
    public static void main(String[] args) {
        String name = "study";
        // JDK7的新特性,表达式的结果可以是字符串!!!
        // 字符的本质还是数字
        /*
        反编译 java -- class(字节码文件) --- 反编译(IDEA)
         */
        switch(name){
            case "hello":
                System.out.println("你好");
                break;
            case "study":
                System.out.println("study");
              break;
            default :
                System.out.println("无法匹配");
                break;
        }
    }
}

class文件反编译后:

package com.jh.struct;

public class SwitchDemo02 {
    public SwitchDemo02() {
    }
    public static void main(String[] args) {
        String name = "study";
        byte var3 = -1;
        switch(name.hashCode()) {
        case 99162322:
            if (name.equals("hello")) {
                var3 = 0;
            }
            break;
        case 109776329:
            if (name.equals("study")) {
                var3 = 1;
            }
        }
        switch(var3) {
        case 0:
            System.out.println("你好");
            break;
        case 1:
            System.out.println("study");
            break;
        default:
            System.out.println("无法匹配");
        }
    }
}

循环结构

为了执行代码中的重复步骤,减少代码的冗余,使代码简洁明了

while 循环

while 是最基本的循环

结构:

while (布尔表达式) {
    // 循环内容
}

只要布尔表达式为 true,循环就会一直执行下去

我们大多数情况是会让循环停止下来的,我们需要一个让表达式失效的方法来结束循环

少部分情况需要循环一直执行,比如服务器的请求响应监听等

循环条件一直为true就会造成无限循环【死循环】我们正常的业务编程中应该尽量避免死循环。会影响程序性能或者造成程序卡死崩溃!

代码:

public class WhileDemo01 {
    public static void main(String[] args) {
        // 输出1~100
        int i = 0;
        while (i < 100) { // 循环结束条件
            i++;
            System.out.println(i);
        }
    }
}

死循环代码:

public class WhileDemo02 {
    public static void main(String[] args) {
        // 死循环
        while (true){
            // 等到客户端连接
            // 定时检查任务
            // ……
        }
    }
}

练习:计算 1 + 2 + 3 + …… + 100 = ?

高斯的故事:首项加末项乘以项数除以2

public class WhileDemo03 {
    public static void main(String[] args) {
        int i = 0; // 初始值
        int sum = 0; //总和
        while (i <= 100) { // 循环条件
            sum += i; // 执行一次 sum 就加上 i
            i++; // i自增
        }
        System.out.println(sum); // 5050
    }
}

do...while 循环

对于 while 语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次

do...while 循环和 while 循环相似,不同的是,do...while 循环至少会执行一次

语法:

do {
    // 代码语句
} while (布尔值表达式);

while 和 do-while 的区别:

  • while先判断后执行。do-while是先执行后判断!
  • do ... while 总是保证循环体会被至少执行一次!

代码:

public class DoWhileDemo01 {
    public static void main(String[] args) {
        int i = 0;
        int sum = 0;
        do {
            sum += i;
            i++;
        } while (i <= 100);
        System.out.println(sum);
    }
}

while 和 do...while 对比:

public class DoWhileDemo02 {
    public static void main(String[] args) {
        int i = 0;
        while (i < 0) {
            System.out.println(i);
        }
        System.out.println("==========");
        do {
            System.out.println(i);
        } while (i < 0);
    }
}
// 输出
==========
0

for 循环

虽然所有循环结构都可以用 while 或者 do...while表示,但 Java 提供了另一种语句 ----- for 循环,使一些循环结构变得更加简单

for 循环语句是支持迭代的一种通用结构,是最有效、最灵活的循环结构

for 循环执行的次数是在执行前就确定的

语法:

for (初始值; 布尔表达式; 更新) {
    // 代码语句
}

for 循环特点:

  1. 最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句
  2. 然后,检测布尔表达式的值。如果为true,循环体被执行。如果alse,循环终止,开始执行循环体后面的语句
  3. 执行一次循环后,更新循环控制变量(迭代因子控制循环变量的地减)
  4. 再次检测布尔表达式。箭环执行上面的过程

代码:

public class ForDemo01 {
    public static void main(String[] args) {
        int a = 1; // 初始化条件
        while (a <= 100) { // 条件判断
            System.out.println(a); //循环体内容
            a++; // 迭代
        }
        System.out.println("while循环结束!");
        // 初始化条件;条件判断;迭代
        for (int i = 1; i <= 100; i++) {
            System.out.println(i);
        }
        System.out.println("for循环结束!");
    }
}

for 循环的死循环写法:

for (; ; ) {
    
}

for循环练习

计算0到100之间的偶数和奇数的和

public class ForDemo02 {
    public static void main(String[] args) {
        // 计算0到100之间的偶数和奇数的和
        int oddSum = 0;
        int evenSum = 0;

        for (int i = 0; i <= 100; i++) {
            if (i % 2 != 0) { // 奇数
                oddSum += i;
            } else { // 偶数
                evenSum += i;
            }
        }
        System.out.println("奇数和:" + oddSum); // 2500
        System.out.println("偶数和:" + evenSum); // 2550
    }
}

用 while 或 for 循环输出 1~1000 之间能被5整除的数,并且每行输出3个

public class ForDemo03 {
    public static void main(String[] args) {
        // 用 while 或 for 循环输出 1~1000 之间能被5整除的数,并且每行输出3个
        for (int i = 1; i <= 1000; i++) {
            if (i % 5 == 0) { // 被5整除
                System.out.print(i + "	");
            }
            if (i % (5 * 3) == 0) { // 每行三个 换行
                System.out.println();
            }
        }
    }
}

打印九九乘法表

public class ForDemo04 {
    public static void main(String[] args) {
        // 外围for循环 控制列
        // 内层for循环 控制每列打印几行
        // 每列打印的行数就是对应的第几列 (1列1行、2列2行、3列3行、……)
        for (int i = 1; i <= 9; i++) { // 控制列
            for (int j = 1; j <= i; j++) { // 控制行
                System.out.print(j + "*" + i + "=" + (i * j) + "	"); // 输出
            }
            System.out.println(); // 换行
        }
    }
}

增强for循环

在Java5中引入了一种主要用于数组或集合的增强型for循环

语法:

for (声明语句 : 表达式) {
   // 代码语句
}

声明语句:声明新的局部变量,该变量的类型必须和数据元素的类型匹配。其作用域限定在循环语句块,其值于此时数组元素的值相等。

表达式:表达式是要访问的数组名,或者是返回值为数组的方法。

代码:

public class ForDemo05 {
    public static void main(String[] args) {
        // 定义一个数组
        int[] numbers = new int[]{10, 20, 30, 40, 50};
        // for循环 遍历数组的元素
        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }
        // foreach 遍历数组的元素
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

break和continue

break在任何循环语句的主体部分,均可用break控制循环的流程。break用于强行退出循环,不执行循环中剩余的语句。(break语句也在switch语句中使用)。

break:

public class BreakDemo {
    public static void main(String[] args) {
        int i = 0;
        while (i < 100) {
            i++;
            System.out.println(i);
            if (i == 30) {
                break; // 终止循环
            }
        }
        // 终止循环后,不影响后面语句的执行
        System.out.println("123"); 
    }
}

continue语句用在循环语句体中,用于终止某次循环过程,即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定。

continue:

public class ContinueDemo {
    public static void main(String[] args) {
        int i = 0;
        while (i < 100) {
            i++;
            if (i % 10 == 0) {
                System.out.println();
                continue; // 终止本次循环,开始下一次循环
            }
            System.out.println(i);
        }
    }
}

关于goto关键字

goto关键字很早就在程序设计语言中出现。尽管goto仍是Java的一个保留字,但并未在语言中得到正式使用;Java没有goto。然而,在break和continue这两个关键字的身上,我们仍然能看出一些goto的影子---带标签的break和continue。

“标签”是指后面跟一个冒号的标识符,例如​ ​:label:

对Java来说唯一用到标签的地方是在循环语句之前。而在循环之前设置标签的唯一理由是:我们希望在其中嵌套另-个循环,由于break和continue关键字通常只中断当前循环,但若随同标签使用,它们就会中断到存在标签的地方。

代码:

public class LabelDemo {
    public static void main(String[] args) {
        // 打印101~150之间的所有质数
        // 质数,大于1的自然数中,除了1和它本身以外不再有其他因数的自然数
        int count = 0;
        // 不建议使用
        outer:for (int i = 101; i < 150; i++) {
            for (int j = 2; j < i / 2; j++) {
                if (i % j == 0){
                    continue outer;
                }
            }
            System.out.println(i);
        }
        System.out.println(count);
    }
}

流程控制练习

打印三角形

public class TestDemo {
    /*
            *
           ***
          *****
         *******
        *********
     */
    public static void main(String[] args) {
        // 打印三角形 5行
        int row = 5;
        for (int i = 1; i <= row; i++) { // 控制行
            for (int j = row; j >= i ; j--) { // 打印最左边空白三角形
                System.out.print(" ");
            }
            for (int j = 1; j <= i ; j++) { // 打印右直角三角形
                System.out.print("*");
            }
            for (int j = 1; j < i ; j++) { // 打印左直角三角形
                System.out.print("*");
            }
            System.out.println(); // 换行
        }
    }
}
懂不懂,都是收获
原文地址:https://www.cnblogs.com/paidaxing0623/p/14128685.html