Java学习笔记②——Java流程控制(一)

目录

image

1. 用户交互Scanner

1.1. Scanner对象

java.util.Scanner——Java提供的工具类,可以获取用户的输入。

基本语法

Scanner s = new Scanner(System.in);

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

next()

package com.matrix.study.scanner;

import java.util.Scanner;

public class Demo01 {

    public static void main(String[] args) {

        //创建一个扫描器对象,用于接受键盘数据
        Scanner scanner = new Scanner(System.in);

        System.out.println("使用next方式接收: ");

        //判断用户有没有接受字符串
        if (scanner.hasNext()){
            //使用next方式接收
            String str = scanner.next();//程序会等待用户输入
            System.out.println("输出内容为:"+str);
        }
        /*
        使用next方式接收:
        hello world
        输出内容为:hello
                */
        //凡是属于IO流的类如果不关闭会一直占用资源,要养成用完就关闭的习惯
        scanner.close();;
    }

}

nextLine()

package com.matrix.study.scanner;

import java.util.Scanner;

public class Demo02 {

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

        System.out.println("使用nextLine方式接收: ");

        if (scanner.hasNextLine()){
            //使用nextLine方式接收
            String str = scanner.nextLine();//程序会等待用户输入
            System.out.println("输出内容为:"+str);
        }
        /*
        使用nextLine方式接收:
        hello world
        输出内容为:hello world
        */
        scanner.close();
    }
}

两者比较:

  • next():

    1. 一定要读取到有效字符后才可以结束;
    2. 对输入有效字符之前遇到的空白,next()会自动将其去掉;
    3. 只有输入有效字符才将后面输入的空白作为分隔符或者结束符;
    4. next()不能得到带有空格的字符串。
  • nextLine():

    1. 以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符;
    2. 可以获得空白

Scanner实例两则:

package com.matrix.study.scanner;

import java.util.Scanner;

public class Demo03 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        //从键盘接收数据
        int i = 0;
        float f = 0.0f;

        System.out.println("请输入整数:");

        if (scanner.hasNextInt()){
            i = scanner.nextInt();
            System.out.println("整数数据:" + i);
        }else {
            System.out.println("输入的不是整数数据");
        }

        System.out.println("请输入小数:");

        if (scanner.hasNextFloat()){
            f = scanner.nextFloat();
            System.out.println("小数数据:" + f);
        }else {
            System.out.println("输入的不是小数数据");
        }

        scanner.close();
    }
}

package com.matrix.study.scanner;

import java.util.Scanner;

public class Demo04 {
    public static void main(String[] args) {
        //输入多个数字,求其总和与平均数,每输入一个数字用回车确认,通过输入非数字结束输入并输出;

        Scanner scanner = new Scanner(System.in);

        //和
        double sum = 0;
        //计算输入了多少个数据
        int m = 0;

        //通过循环判断是否还有输入,并在里面对每一次进行求和和统计
        while (scanner.hasNextDouble()){
            double x = scanner.nextDouble();
            m = m + 1;
            sum = sum + x;
            System.out.println("你输入了第"+m+"个数据,当前的结果为"+sum);
        }

        System.out.println(m + "个数的和为" + sum);
        System.out.println(m + "个数的Avg为" + (sum/m));

        scanner.close();
    }
}

2.顺序结构

  • Java的基本结构就是顺序结构,除非特别指明,否则就按照顺序一句一句执行。
  • 顺序结构是最简单的算法结构。

image

  • 语句与语句之间,框与框之间是按从上到下的顺序进行的,它是由若干个依次执行的处理步骤组成的,它是任何一个算法都离不开的一种基本算法结构

3.选择结构

image

3.1. if单选择结构

我们很多时候需要判断一个东西是否可行,然后我们才去执行,这样的过程用if语句执行。

image

if(布尔表达式){
    //如果布尔表达式为true将执行的语句
}
package com.matrix.study.structure.selective_structure;

import java.util.Scanner;

public class IfDemo01 {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入内容:");
        String s = scanner.nextLine();

        //equals:判断字符串是否相等
        if (s.equals("hello")){
            System.out.println(s);
        }
        System.out.println("End");

        scanner.close();
    }
}

3.2. if双选择结构

两个判断,双选择结构:if-else结构

image

if(布尔表达式){
    //如果布尔表达式为true将执行的语句
}else{
    //如果布尔表达式为false将执行的语句
}
package com.matrix.study.structure.selective_structure;import java.util.Scanner;public class IfDemo02 {    public static void main(String[] args) {        //考试分数大于60就是及格,小于60就是不及格        Scanner scanner = new Scanner(System.in);        System.out.println("请输入成绩:");        int score = scanner.nextInt();        if (score>60){            System.out.println("及格");        }else {            System.out.println("不及格");        }        scanner.close();    }}

3.3. if多选择结构

语法:

if(布尔表达式1){    //如果布尔表达式为true将执行的语句}else if(布尔表达式1){    //如果布尔表达式为true将执行的语句}else if(布尔表达式2){    //如果布尔表达式为true将执行的语句}else{    //如果以上布尔表达式都不为true将执行的语句}

image

实例:

package com.matrix.study.structure.selective_structure;import java.util.Scanner;public class IfDemo03 {    public static void main(String[] args) {    //考试分数大于60就是及格,小于60就是不及格    Scanner scanner = new Scanner(System.in);    System.out.println("请输入成绩:");    int score = scanner.nextInt();    if (score==100){        System.out.println("恭喜满分");    }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<60 && score>=0){        System.out.println("不及格");    }else {        System.out.println("输入错误,成绩不合法");    }    scanner.close();    }}

注意

  • if语句至多有一个else语句,else语句在所有else if 语句之后。
  • if语句可以有若干个else if 语句,它们必须在else语句之前。
  • 一旦其中一个else if 语句检测为true,其它的else if 语句以及else语句都将跳过。

3.4. 嵌套的if结构

语法:

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

3.5. switch多选择结构

  • 多选择结构还有一个实现方式就是switch case语句。
  • switch case语句判断一个变量与一系列值中某个值是否相等,每个值为一个分支。
  • 看源码
  • switch 语句中的变量类型可以是:
    • byte,short, int,char
    • 字符串String,字符的本质还是数字
    • case标签必须为字符串常量或字面量
switch(expression){    case value:        //语句        break;//可选    case value:        //语句        break;//可选    //你可以有任意数量的case语句    default ://可选         //语句}
package com.matrix.study.structure.selective_structure;public class SwitchDemo01 {    public static void main(String[] args) {        //case 穿透   //switch 匹配一个具体的值        char grade = '去';        switch (grade){            case 'A':                System.out.println("优秀");                break;//可选            case 'B':                System.out.println("良好");                break;//可选            case 'C':                System.out.println("及格");            case 'D':                System.out.println("再接再厉");            case 'E':                System.out.println("挂科");                break;//可选            case 'F':                System.out.println("爪巴");            default:                System.out.println("未知等级");        }    }}
package com.matrix.study.structure.selective_structure;public class SwitchDemo02 {    public static void main(String[] args) {        String name = "ks";        //反编译 Java——class(字节码文件)——反编译(IDEA)        switch (name){            case "ads":                System.out.println("asda");                break;            case "ks":                System.out.println("ks");                break;            default:                System.out.println("???");        }    }}

4. 循环结构

image

4.1. while循环

  • while是最基本的循环,它的结构为

    while(布尔表达式){    //循环内容}
    
  • 只要布尔表达式为true,循环就会一直执行下去。

image

package com.matrix.study.structure.cycle_structure;public class WhileDemo01 {    public static void main(String[] args) {        //输出1~100        int i = 0;        while(i<100){            i++;            System.out.println(i);        }    }}
package com.matrix.study.structure.cycle_structure;public class WhileDemo02 {    public static void main(String[] args) {        //计算1+2+3+...+100 = ?        int i = 0;        int sum = 0;        while (i<=100){            sum = sum + i;            i++;        }        System.out.println(sum);    }}

4.2. do...while循环

  • 对于while语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件也至少执行一次。
  • do...while循环和while循环相似,不同的是,do...while循环至少会执行一次。
do{    //代码语句}while(布尔表达式)
package com.matrix.study.structure.cycle_structure;public class DoWhileDemo01 {    public static void main(String[] args) {        int i = 0;        int sum = 0;        do {            sum = sum + i;            i++;        }while (i<=100);        System.out.println(sum);    }}
package com.matrix.study.structure.cycle_structure;public class DoWhileDemo02 {    public static void main(String[] args) {        int a = 0;        while (a<0){            System.out.println(a);            a++;        }        System.out.println("################");        do {            System.out.println(a);            a++;        }while (a<0);    }}
  • do...while循环和while循环的区别
    • while先判断后执行。dowhile是先执行后判断!
    • dowhile总是保证循环体被至少执行一次!这是他们的主要差别。

4.3. For循环

  • for循环是支持迭代的一种通用结构,是最有效,最灵活的循环结构。
  • for循环执行的次数是在执行前就确定的。语法格式如下:
for(初始化;布尔表达式;更新){    //代码语句}
package com.matrix.study.structure.cycle_structure;public class ForDemo01 {    public static void main(String[] args) {        int a = 1;//初始化条件        while (a<=100){//条件判断            System.out.println(a);//循环体            a+=2;//迭代        }        System.out.println("while循环结束了");        /*        关于for循环有以下几点说明:        最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句        然后,检测布尔表达式的值。如果为true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。        执行一次循环后,更新循环控制变量(迭代因子控制循环变量的增减)。        再次检测布尔表达式,循环执行上面的语句         */        //初始化//条件判断//迭代        for (int i=1;i<=100;i++){            System.out.println(i);        }        System.out.println("for循环结束了");    }}
package com.matrix.study.structure.cycle_structure;public class ForDemo02 {    //计算0~100之间的奇数和偶数的和    public static void main(String[] args) {        int sumOdd = 0;        int sunEven = 0;        for (int j = 0; j <= 100; j++) {            if (j % 2 == 1){                sunEven += j;            }            else{                sumOdd += j;            }        }        System.out.println(sunEven);        System.out.println(sumOdd);    }}
package com.matrix.study.structure.cycle_structure;public class ForDemo03 {    //用while或for循环输出1-1000间能被5整除的数,并且每行输出3个    public static void main(String[] args) {        for (int i = 1; i <= 1000; i++) {            if (i%5 == 0 && i%3 == 0){//i%(5*3)==0                System.out.println(i);            }else if (i%5 == 0){                System.out.print(i + "\t");            }        }    }}
package com.matrix.study.structure.cycle_structure;public class ForDemo04 {    public static void main(String[] args) {        //打印九九乘法表        for (int i = 1; i <= 9; i++) {            for (int j = 1; j <= i; j++) {                if (i!=j){                    System.out.print(j+"*"+i+"="+(i*j)+" ");                }else {                    System.out.println(j+"*"+i+"="+(i*j));                }                /*                System.out.print(j+"*"+i+"="+(i*j)+"\t");}                System.out.println()                 */            }        }    }}

4.4. 增强for循环

  • 主要用于数组或集合

  • 语法格式如下:

    for(声明语句 : 表达式){    //代码语句}
    
  • 声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。

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

package com.matrix.study.structure.cycle_structure;public class ForDemo05 {    public static void main(String[] args) {        int[] numbers = {10,20,30,40,50};//定义了一个数组        for (int i = 0; i < 5 ; i++) {            System.out.println(numbers[i]);        }        System.out.println("+++++++++++++++++++++++");        //遍历数组的元素        for (int x : numbers) {            System.out.println(x);        }    }}

5. break & continue

image

package com.matrix.study.structure.cycle_structure;public class ContinueDemo01 {    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);        }        //break在任何循环语句的主体部分,均可用break控制循环的流程        //      break用强行退出循环,不执行循环中剩余的语句。(break语句也在switch语句中使用)        //continue 语句用在循环语句体中,用于终止某次循环过程,即跳过循环体中尚未执行的语句,        //      接着进行下一次是否执行循环的判定        //    }}
posted @ 2021-07-27 21:26  Jason_Matrix  阅读(29)  评论(0)    收藏  举报