Java 流程控制学习(B站UP主遇见狂神说学习笔记)

Java流程控制

用户交互Scanner

  • java.util.Scanner 是Java5的新特性,我们可以通过Scanner类来获取用户输入

  • 基本语法:

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

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

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

    • 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。

    • next()不能得到带有空格的字符串。

    • package com.hao.scanner;
      
      import java.util.Scanner;
      
      /**
       * @program: JavaSE
       * @description:
       * @author: HuMingHao
       * @create: 2021-03-29 14:40
       **/
      public class Demo01 {
          public static void main(String[] args) {
              // 创建一个扫描器对象,用于接收键盘数据
              Scanner scanner = new Scanner(System.in);
      
              System.out.println("使用next方式接收:");
      
              // 判断用户有没有输入字符串
              if(scanner.hasNext()){
                  // 使用next方式接收:
                  String next = scanner.next();// 程序会等待用户输入完毕
                  System.out.println("输出的内容为:"+next);
              }
      
              // 凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉。
              scanner.close();
      
          }
      }
      
使用next方式接收:
hello world
输出的内容为:hello
  • nextLine()
    • 以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前所有字符。
    • 可以获得空白
package com.hao.scanner;

import java.util.Scanner;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-03-29 15:00
 **/
public class Demo02 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

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

        if (scanner.hasNextLine()){
            String str = scanner.nextLine();
            System.out.println("输出的内容为:"+str);
        }



    }
}
使用nextLine方式接收:
hello world
输出的内容为:hello world
package com.hao.scanner;

import java.util.Scanner;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-03-29 15:15
 **/
public class Demo03 {
    public static void main(String[] args) {
        // 从键盘接收数据
        Scanner scanner = new Scanner(System.in);

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

        String str = scanner.nextLine();

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

        scanner.close();

    }
}
请输入数据:
欢迎大家来到美丽的泰国
输出的内容为:欢迎大家来到美丽的泰国
  • 举例:

    package com.hao.scanner;
    
    import java.util.Scanner;
    
    /**
     * @program: JavaSE
     * @description:
     * @author: HuMingHao
     * @create: 2021-03-29 15:33
     **/
    public class Demo05 {
        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++;
                sum+=x;
                System.out.println("你输入了第"+m+"个数据,然后当前结果sum="+sum);
            }
    
            System.out.println(m+"个数的和位"+sum);
            System.out.println(m+"个数的平均值是"+(sum/m));
    
    
    
            scanner.close();
    
        }
    }
    
10
你输入了第1个数据,然后当前结果sum=10.0
20
你输入了第2个数据,然后当前结果sum=30.0
30
你输入了第3个数据,然后当前结果sum=60.0
a
3个数的和位60.0
3个数的平均值是20.0

顺序结构

  • JAVA的基本结构就是顺序结构,除非特别指明,否则就是按照顺序一句一句执行。
  • 顺序结构是最简单的算法结构;
  • 语句和语句之间,框与框之间是按从上到下的顺序进行的,它是由若干个依次执行的处理步骤组成的,它是任何一个算法都离不开的一种基本算法结构。

选择结构

  • if单选择结构
  • if双选择结构
  • if多选择结构
  • 嵌套的if结构
  • switch多选择结构

if单选择结构

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

  • 语法:

    if(布尔表达式){
    // 如果布尔表达式为true将执行的语句
    }
    
    package com.hao.structure;
    
    import java.util.Scanner;
    
    /**
     * @program: JavaSE
     * @description:
     * @author: HuMingHao
     * @create: 2021-03-30 13:37
     **/
    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();
    
        }
    }
    
请输入内容:
Hello
Hello
End

if双选择结构

  • 那现在有个需求,公司要收购一个软件,成功了,给人支付100万元,失败了,自己找人开发,这样的需求用一个if就搞不定了,我们需要有两个判断,需要一个双选择结构,所以有了if-else结构

  • 语法:

    if(布尔表达式){
    	// 如果布尔表达式的值为true
    }else{
    	// 如果布尔表达式的值为false
    }
    
    package com.hao.structure;
    
    import java.util.Scanner;
    
    /**
     * @program: JavaSE
     * @description:
     * @author: HuMingHao
     * @create: 2021-03-30 13:43
     **/
    public class IfDemo02 {
        public static void main(String[] args) {
            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();
        }
    }
    
请输入成绩:
60
及格

if多选择结构

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

  • 语法:

    if(布尔表达式1){
    	// 如果布尔表达式 1 的值为true执行代码
    }else if(布尔表达式2){
    	// 如果布尔表达式 2 的值为true执行代码
    }else if(布尔表达式3){
    	// 如果布尔表达式 3 的值为true执行代码
    }else{
    	// 如果布尔表达式都不为true执行代码
    }
    
    package com.hao.structure;
    
    import java.util.Scanner;
    
    /**
     * @program: JavaSE
     * @description:
     * @author: HuMingHao
     * @create: 2021-03-30 16:49
     **/
    public class IfDemo03 {
        public static void main(String[] args) {
            /*
            if 语句至多有1个else语句,else 语句在所有的else if 语句之后。
            if 语句可以有若干个else if 语句,它们必须在else 语句之前。
            一旦其中一个else if 语句检测为true,其他else if 以及else语句都将跳过执行
             */
            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();
        }
    }
    
请输入成绩:
80
及格

嵌套的if结构

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

  • 语法:

    if(布尔表达式1){
    	// 如果布尔表达式 1的值为true执行代码
    	if(布尔表达式2){
    	// 如果布尔表达式 2的值为true执行代码
    	}
    }
    
    package com.hao.structure;
    
    /**
     * @program: JavaSE
     * @description:二分查找
     * @author: HuMingHao
     * @create: 2021-03-30 23:49
     **/
    public class test {
        public static void main(String[] args) {
            // 准备好一个有序的被查找数组
            int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            // 调用查找方法查找给定数组中5元素所在的索引值,并接收查找到的索引
            int index = getIndex(arr, 5);
            // 输出索引
            System.out.println("index:" + index);
        }
    
        public static int getIndex(int[] arr, int num) {
            // 定义变量,表示查找数组范围的最左侧,先从0索引开始
            int left = 0;
            // 定义变量,表示查找数组范围的最右侧,先从最大索引开始
            int right = arr.length - 1;
            // 定义变量,表示查找范围的中间值
            int mid;
            while (left <= right) {
                // 中间索引 = (左侧  + 右侧) / 2
                // mid = (left + right) / 2;
                // 为了提高效率,我们可以用位运算代替除以运算
                mid = (left + right) >> 1;
                if (arr[mid] > num) {
                    //如果中间元素大于要查找元素,则在中间元素的左侧去找正确元素,最右侧变为mid - 1
                    right = mid - 1;
                } else if (arr[mid] < num) {
                    //如果中间元素小于要查找元素,则在中间元素的右侧去找正确元素,最左侧变为mid + 1
                    left = mid + 1;
                } else {
                    // 如果不大不小,那么就正好是找到了,返回找到的索引
                    return mid;
                }
            }
            // 当查找范围的最左侧和最右侧重叠后还没有找到元素,则返回-1表示没有找到
            return -1;
        }
    }
    

switch多选择结构

  • 多选择结构还有一个实现方式就是switch case语句
  • switch case语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。
  • switch语句中的变量类型可以是:
  • byte,short,int或者char
  • 从Java SE 7 开始
  • switch支持字符串String类型了
  • 同时case标签必须为字符串常量和字面量
switch(expression){
	case value:
	// 语句
	break;//可选
	case value:
	//语句
	break;// 可选
	// 你可以有任意数量的case语句
	default:// 可选
	// 语句
}
  • 每一个对象都会有hashcode,通过特定算法生成的
  • 哈希是通过特点算法,给每一个“东西”,一个唯一的值
  • 从 *.class 逆向得到 *.java 的过程,称为反编译。
package com.hao.structure;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-03-31 09:13
 **/
public class SwitchDemo01 {
    public static void main(String[] args) {
        // case穿透 switch 匹配一个具体值
        char grade = 'F';

        switch (grade){
            case 'A':
                System.out.println("优秀");
                break;
            case 'B':
                System.out.println("良好");
                break;
            case 'C':
                System.out.println("及格");
                break;
            case 'D':
                System.out.println("再接再厉");
                break;
            case 'E':
                System.out.println("挂科");
                break;
            default:
                System.out.println("未知等级");
        }
    }
}
package com.hao.structure;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-03-31 09:41
 **/
public class SwitchDemo02 {
    public static void main(String[] args) {
        String name = "小浩浩";
        // JDK7的新特性,表达式结果可以是字符串!!!
        // 字符的本质还是数字

        // 反编译 java--class(字节码文件)--反编译(IDEA)
        switch(name){
            case "浩浩":
                System.out.println("胡明浩");
                break;
            case "小浩浩":
                System.out.println("明浩");
                break;
            default:
                System.out.println("弟弟");

        }
    }
}

循环结构

  • while循环

  • do…while循环

  • for循环

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

while循环

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

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

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

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

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

  • 思考:计算1+2+3+…+100=?

package com.hao.structure;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-03-31 11:33
 **/
public class WhileDemo01 {
    public static void main(String[] args) {
        // 输出1-100
        int i = 0;
        while (i<100){
            i++;
            System.out.println(i);
        }

    }
}
package com.hao.structure;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-03-31 13:46
 **/
public class WhileDemo03 {
    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);
    }
}

do…while循环

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

  • do-while循环和while循环相似,不同的是,do…while至少会执行一次。

  • do{
       // 代码语句
       
    }while(布尔表达式);
    
  • while和do-While的区别:

    • while先判断后执行。dowihile是先执行后判断!
    • Do…while总是保证循环体会被至少执行一次!这是他们的主要差别,
package com.hao.structure;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-03-31 23:28
 **/
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.hao.structure;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-03-31 23:31
 **/
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);
    }
}
=================
0

For 循环

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

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

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

  • for(初始化;布尔表达式;更新){
        // 代码语句
    }
    
  • package com.hao.structure;
    
    /**
     * @program: JavaSE
     * @description:
     * @author: HuMingHao
     * @create: 2021-03-31 23:54
     **/
    public class ForDemo02 {
        // 练习1:计算0到100之间奇数和偶数的和
        public static void main(String[] args) {
            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);
            System.out.println("偶数的和:"+evenSum);
    
        }
    }
    
奇数的和:2500
偶数的和:2550
  • package com.hao.structure;
    
    /**
     * @program: JavaSE
     * @description:
     * @author: HuMingHao
     * @create: 2021-04-01 14:34
     **/
    public class ForDemo03 {
        public static void main(String[] args) {
            // 练习2:用while或for循环输出1-1000之间能被5整除的数,并且每行输出3个
    
            for (int i = 1; i <= 1000; i++) {
                if(i%5==0){
                    System.out.print(i+"\t");
                }
                if(i%(5*3)==0){
                    System.out.println();
                    // System.out.print("\n");
                }
            }
            // println 输出完会换行
            // print 输出完不会换行
        }
    }
    
5	10	15	
20	25	30	
35	40	45	
50	55	60	
65	70	75	
80	85	90	
95	100	105	
110	115	120	
125	130	135	
140	145	150	
155	160	165	
170	175	180	
185	190	195	
200	205	210	
215	220	225	
230	235	240	
245	250	255	
260	265	270	
275	280	285	
290	295	300	
305	310	315	
320	325	330	
335	340	345	
350	355	360	
365	370	375	
380	385	390	
395	400	405	
410	415	420	
425	430	435	
440	445	450	
455	460	465	
470	475	480	
485	490	495	
500	505	510	
515	520	525	
530	535	540	
545	550	555	
560	565	570	
575	580	585	
590	595	600	
605	610	615	
620	625	630	
635	640	645	
650	655	660	
665	670	675	
680	685	690	
695	700	705	
710	715	720	
725	730	735	
740	745	750	
755	760	765	
770	775	780	
785	790	795	
800	805	810	
815	820	825	
830	835	840	
845	850	855	
860	865	870	
875	880	885	
890	895	900	
905	910	915	
920	925	930	
935	940	945	
950	955	960	
965	970	975	
980	985	990	
995	1000
  • 九九乘法表

    package com.hao.structure;
    
    /**
     * @program: JavaSE
     * @description:
     * @author: HuMingHao
     * @create: 2021-04-01 14:42
     **/
    public class ForDemo04 {
        public static void main(String[] args) {
            // 1.我们先打印第一列,这个大家应该都会
            // 2.我们把固定的1再用一个循环包起来
            // 3.去掉重复项 i<=j
            // 4.过一遍循环换一行
            for (int j = 1; j <=9; j++) {
                for (int i = 1; i <=j; i++) {
                    System.out.print(i+"*"+j+"="+(j*i)+"\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	

增强for循环

  • 这里我们先只是见一面,做个了解,之后数组我们重点使用。

  • java5引入了一种主要用于数组或集合的增强型for循环。

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

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

package com.hao.structure;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-04-02 16:19
 **/
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);
        }
    }
}

break continue 标签

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

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

  • 关于goto关键字(它不是关键字,是保留字)

    • goto关键字很早就在程序设计语言中出现。尽管goto仍是java的一个保留字,但并未在语言中得到正式的使用;
    • 标签是指后面跟一个冒号的标识符,例如:label:
    • 对java来说唯一用到标签的地方是在循环语句之前。而在循环之前设置标签的唯一理由是:我们希望在其中嵌套另一个循环,由于break和continute关键字通常只中断当前循环,但若随同标签使用,它们就会中断存在标签的地方。
package com.hao.structure;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-04-02 16:31
 **/
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");
    }
}
package com.hao.structure;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-04-02 16:34
 **/
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.print(i);
        }
    }
}
package com.hao.structure;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-04-02 17:13
 **/
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.print(i+" ");
        }

    }
}

打印三角形

package com.hao.structure;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

/**
 * @program: JavaSE
 * @description:
 * @author: HuMingHao
 * @create: 2021-04-04 23:57
 **/
public class TestDemo {
    public static void main(String[] args) {
        // 打印三角形 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();
        }
        
    }
}
     *
    ***
   *****
  *******
 *********
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值