2021.2.22_JAVA流程控制

JAVA流程控制

用户交互Scanner

  • JAVA提供了一个工具类来获取用户的输入。java.util.Scanner

  • 基本语法:

    Scanner s = new Scanner(System.in);
    
  • 可以通过Scanner类的next()和nextLine()方法获取输入的字符串,在读取前一般需要使用hasNext()以及hasNextLine()方法来判断是否还有残余的输入数据需要读取。

package Scanner;

import java.util.Scanner;

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

        //创建一个扫描器的对象
        Scanner s1 = new Scanner(System.in);

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

        // 判断用户是否输入内容
        if (s1.hasNext()) {
            // 使用next方法接收
            String input = s1.next();
            System.out.println("输入的内容为:" + input);
        }


        //创建另一个扫描器的对象
        Scanner s2 = new Scanner(System.in);

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

        if (s2.hasNextLine()) {
            // 使用nextLine方法接收
            String input = s2.nextLine();
            System.out.println("输入的内容为:" + input);
        }

        // 凡是和i/o流相关的类都要有关闭的习惯
        s1.close();
        s2.close();

    }
}

//        使用next方法接收:
//        hello honey
//        输入的内容为:hello
//        使用nextLine方法接收:
//        hello honey
//        输入的内容为:hello honey
  • 也可以通过newInt()等方法接收数值数据。
package Scanner;

import java.util.Scanner;

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

        int i = 0;
        float f = 0.0F;

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

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


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

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

        s1.close();
    }
}

//        请输入整数:
//        10
//        整数数据为:10
//        10.11
//        小数数据为:10.11

以下是一个求平均值的小程序演示,

package Scanner;

/*
    输入多个数值,求其总和以及平均数,每输入一个数字用回车确认,通过非数字来结束输入并输出结果
 */

import java.util.Scanner;

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

        // 数字总和
        double sum = 0;
        // 数字个数
        int numOfNumbers = 0;

        System.out.println("输入多个数值,求其总和以及平均数,每输入一个数字用回车确认,通过非数字来结束输入并输出结果: ");

        while (s.hasNextDouble()) {
            sum += s.nextDouble();
            numOfNumbers += 1;
        }

        System.out.println("Sum of the numbers is: " + sum);
        System.out.println("Average of the numbers is: "+ (sum/numOfNumbers));

        s.close();
    }
}


//输入多个数值,求其总和以及平均数,每输入一个数字用回车确认,通过非数字来结束输入并输出结果:
//3
//5
//7
//89
//2
//4
//5
//3
//k
//Sum of the numbers is: 118.0
//Average of the numbers is: 14.75

顺序结构

  • java的基本结构就是顺序结构,除非特别指明,否则就按顺序一句一句执行。
  • 顺序结构是最简单的算法结构。
  • 语句与语句之间,框与框之间是按从上到下的顺序进行的,它是任何算法的基本结构。

顺序结构演示,

package Structure;

public class Demo01 {
    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
//    hello2
//    hello3
//    hello4
//    hello5

选择结构

  • if单选择结构

    if (布尔表达式){

    ​ //如果表达式为true将执行的语句

    }

    package Structure;
    
    import java.util.Scanner;
    
    public class Demo02 {
        public static void main(String[] args) {
            Scanner s1 = new Scanner(System.in);
    
            System.out.println("请输入Yes/No: ");
            String input1 = s1.nextLine();
    
            // equals方法可以判断两个字符串是否相同
            if (input1.equals("Yes")) {
                System.out.println("选择的是Yes");
            }
    
            s1.close();
        }
    }
    
    //        请输入Yes/No:
    //        Yes
    //        选择的是Yes
    
    
  • if双选择结构

    if (布尔表达式){

    ​ //如果表达式为true将执行的语句

    }else{

    ​ //如果表达式为false将执行的语句

    }

    package Structure;
    
    import java.util.Scanner;
    
    public class Demo03 {
        public static void main(String[] args) {
            Scanner s1 = new Scanner(System.in);
    
            System.out.println("请输入你的分数: ");
            int score = s1.nextInt();
    
            if (score >= 60){
                System.out.println("及格了");
            }else {
                System.out.println("不及格");
            }
    
            s1.close();
        }
    }
    
    //        请输入你的分数:
    //        40
    //        不及格
    
  • if多选择结构

    if (布尔表达式1){

    ​ //如果表达式1为true将执行的语句

    }else if (布尔表达式2){

    ​ //如果表达式2为true将执行的语句

    }else if (布尔表达式3){

    ​ //如果表达式3为true将执行的语句

    .

    .

    .

    }else {

    ​ //以上表达式都为false将执行的语句

    }

    package Structure;
    
    import java.util.Scanner;
    
    public class Demo04 {
        public static void main(String[] args) {
    
            int score = 0;
            Scanner s = new Scanner(System.in);
    
            System.out.println("请输入分数: ");
            score = s.nextInt();
    
            if (score < 60) {
                System.out.println("不及格");
            }else if (score >= 80) {
                System.out.println("优");
            }else{
                System.out.println("良");
            }
    
            s.close();
        }
    }
    
    
    //        请输入分数:
    //        72
    //        良
    
  • 嵌套的if结构

    if (布尔表达式1){

    ​ //如果表达式1为true将执行的语句

    ​ if (布尔表达式2){

    ​ //如果表达式2为true将执行的语句

    ​ }

    }

    package Structure;
    
    import java.util.Scanner;
    
    public class Demo5 {
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in);
            int score = 0;
    
            System.out.println("Enter your score");
            score = s.nextInt();
    
            if (score >= 60){
                System.out.println("及格");
                if (score >= 80){
                    System.out.println("优秀");
                }
            }else {
                System.out.println("不及格");
            }
    
            s.close();
        }
    }
    
    //        Enter your score
    //        80
    //        及格
    //        优秀
    
    //        Enter your score
    //        50
    //        不及格
    
    //        Enter your score
    //        70
    //        及格
    
  • switch多选择结构

    switch也是一个实现多选择的语法。

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

    switch语句中的变量类型可以是:byte,short,int,char或者String。

    case标签必须为字符串常量或字面量。

    结构如下,

    switch (expression){

    ​ case value:

    ​ //语句

    ​ break; //可选

    ​ case value:

    ​ //语句

    ​ break; //可选

    ​ //可以有任意数量的case语句

    ​ default: //默认情况,可选

    ​ //语句

    }

    package Structure;
    
    import java.util.Scanner;
    
    public class Demo06 {
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in);
            String grade;
    
            System.out.println("Please enter your grade: ");
            grade = s.next();
    
            switch (grade){
                case "A":
                    System.out.println("Excellent!");
                    break;
                case "B":
                    System.out.println("Good!");
                    break;
                case "C":
                    System.out.println("Pass");
                    break;
                case "D":
                    System.out.println("Failed");
                    break;
                default:
                    System.out.println("Not a valid grade.");
            }
    
            s.close();
        }
    }
    
    //Please enter your grade: 
    //B
    //Good!
    

    这边的break是为了防止case穿透,如果不加break会出现以下现象:

    package Structure;
    
    import java.util.Scanner;
    
    public class Demo06 {
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in);
            String grade;
    
            System.out.println("Please enter your grade: ");
            grade = s.next();
    
            switch (grade){
                case "A":
                    System.out.println("Excellent!");
                case "B":
                    System.out.println("Good!");
                case "C":
                    System.out.println("Pass");
                case "D":
                    System.out.println("Failed");
                default:
                    System.out.println("Not a valid grade.");
            }
    
            s.close();
        }
    }
    
    //Please enter your grade: 
    //B
    //Good!
    //Pass
    //Failed
    //Not a valid grade.
    

循环结构

  • while循环

    while (布尔表达式) {

    ​ //只要布尔表达式为True就执行命令

    }

    大多数情况下会需要一个能让表达式变为false的途径来让循环停下来,避免进入死循环

    package Structure.Loop;
    
    public class Demo01 {
        public static void main(String[] args) {
    
            //输出1到5
    
            int num = 1;
            while (num <= 5){
                System.out.println(num);
                num ++;
            }
        }
    }
    
    //1
    //2
    //3
    //4
    //5
    
    // 1加到100是多少
    
    public class Demo02 {
        public static void main(String[] args) {
             int num = 1;
             int sum = 0;
             while (num <=100) {
                 sum += num;
                 num ++;
             }
    
            System.out.println("result: " + sum);
        }
    }
    
    //result: 5050
    
  • do...while循环

    可以看成至少运行一次的while语句,格式如下:

    do {

    ​ //执行语句

    }while(布尔值表达式);

    public class Demo03 {
        public static void main(String[] args) {
            do {
                System.out.println("只运行一次");
            } while (false);
        }
    }
    
    //只运行一次
    
  • for循环

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

    for循环的格式如下,

    for (初始化; 布尔表达式; 更新){

    ​ //执行语句

    }

    package Structure.Loop;
    
    //计算1~100奇数之和以及偶数之和
    
    public class demo4 {
        public static void main(String[] args) {
    
            int sum_odd = 0;
            int sum_even = 0;
    
            for (int i = 1; i<=100; i++) {
                if (i % 2 == 0){
                    sum_even += i;
                }else{
                    sum_odd += i;
                }
            }
    
            System.out.println("Sum of all odd numbers is " + sum_odd);
            System.out.println("Sum of all even numbers is " + sum_even);
        }
    }
    
    //Sum of all odd numbers is 2500
    //Sum of all even numbers is 2550
    
    package Structure.Loop;
    
    // 打印99乘法表
    
    public class Demo05 {
        public static void main(String[] args) {
    
            for (int i = 1; i<10; i++) {
                for (int j = 1; j<=i; j++) {
                    System.out.print(j + "*" + i + "=" + (i*j) + "\t");
                }
                System.out.println();
            }
        }
    }
    
    //1*1=1	
    //1*2=2	2*2=4	
    //1*3=3	2*3=6	3*3=9	
    //1*4=4	2*4=8	3*4=12	4*4=16	
    //1*5=5	2*5=10	3*5=15	4*5=20	5*5=25	
    //1*6=6	2*6=12	3*6=18	4*6=24	5*6=30	6*6=36	
    //1*7=7	2*7=14	3*7=21	4*7=28	5*7=35	6*7=42	7*7=49	
    //1*8=8	2*8=16	3*8=24	4*8=32	5*8=40	6*8=48	7*8=56	8*8=64	
    //1*9=9	2*9=18	3*9=27	4*9=36	5*9=45	6*9=54	7*9=63	8*9=72	9*9=81	
    
    // 用循环输出1-1000中被5整除的数,并且每行输出3个
    
    public class Demo06 {
        public static void main(String[] args) {
    
            int position = 0;
            for (int i = 1; i <= 1000; i++) {
    
                //每当输入位置到了第4个位置就换行
                if (position == 3) {
                    System.out.println();
                    position = 0; //重新初始化位置参数
                }
    
                if (i % 5 == 0) {
                    System.out.print(i + "\t");
                    position += 1; //输入位置向后移动一格
                }
    
            }
        }
    }
    
    //5	10	15	
    //20	25	30	
    //35	40	45	
    //50	55	60	
    //65	70	75	
    //80	85	90
    //.......
    
  • 增强型for循环

    一种应用于数组和集合的for循环

    增强for循环格式如下:

    for (声明语句 : 表达式){

    ​ //执行语句

    }

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

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

    例子,

    package Structure.Loop;
    
    public class Demo07 {
        public static void main(String[] args) {
    
            int[] numList = {10, 20, 30, 40 ,50}; //数组的定义
    
            //快捷方式:numList + . + for
            for (int x:numList) {        //遍历numList中的元素
                System.out.print(x + "\t");
            }
        }
    }
    
    //10	20	30	40	50
    
  • break & continue

    • break语句可以直接跳出循环语句
    • continue可以直接跳过本次循环,继续下次循环
    package Structure.Loop;
    
    public class Demo08 {
        public static void main(String[] args) {
            for (int i = 0; i < 7; i++) {
                if (i == 4) {
                    break;
                }
                System.out.print(i + "\t");
            }
        }
    }
    
    //0	 1	 2	 3 	
    
    public class Demo08 {
        public static void main(String[] args) {
            for (int i = 0; i < 7; i++) {
                if (i == 4) {
                    continue;
                }
                System.out.print(i + "\t");
            }
        }
    }
    
    //0	 1	 2	 3	 5	 6
    

练习

// draw triangle

public class Demo09 {
    public static void main(String[] args) {
        int size = 5;

        for (int i = 1; i <= 5; i++) {
            for (int j = 5; 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();
        }
    }
}

//    *
//   ***
//  *****
// *******
//*********
posted @ 2021-02-23 01:15  cutomorrow  阅读(51)  评论(0)    收藏  举报