【狂神说Java】2021-03-05学习笔记:java流程控制

Java流程控制

1.用户交互Scanner

2.顺序结构

3.选择结构

4.循环结构

5.break&continue

6.练习

用户交互Scanner

实现程序和人的交互,我们可以通过Scanner类来获取用户的输入

基本语法:Scanner s = new Scanner(System.in);

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

/*
next():
1.一定要读取到有效字符后才可以结束输入
2.对输入有效字符之前遇到的空!白!,next()方法会自动将其去掉   
3.只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符
4.next()不能得到带有空格的字符串
-------------------------------
nextLine():
1.以Enter为结束符,也就是说nextLine()方法返回的是输入回!车!之前的所有字符
2.可以获得空白
*/

例:
import java.util.Scanner;
public class Demo201 {
    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);
        }
        //凡是属于IO流的东西,用完最好关闭,省内存,要不会一直占用资源
        scanner.close();
    }
}
 /*运行结果:
使用next方式接收:
hello world
输出的内容为:hello

Process finished with exit code 0
*/   
    
    
import java.util.Scanner;
public class Demo2012 {
    public static void main(String[] args) {
        //从键盘接收数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用nextLine方式接收:");
        //判断是否还有输入
        if (scanner.hasNextLine()){
            //使用next方式接收
            String str = scanner.nextLine();
            System.out.println("输出的内容为:"+str);
        }
        //凡是属于IO流的东西,用完最好关闭,省内存,要不会一直占用资源
        scanner.close();
    }
}      
/*运行结果:
使用nextLine方式接收:
hello world
输出的内容为:hello world

Process finished with exit code 0
*/



import java.util.Scanner;
public class Demo2013 {
    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();
    }
/*运行结果:
请输入数据:
欢迎学习java 欢迎来到线下学习
输出的内容为:欢迎学习java 欢迎来到线下学习

Process finished with exit code 0
*/  

nextInt()只接收int类型,先输入的话,如果输入其他类型会直接报错,放在if里既可以判断,又可以不报错

import java.util.Scanner;
public class Demo202 {
    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();
    }
/*运行结果:
请输入整数:
10
整数数据:10
请输入小数:
1.1
小数数据:1.1

Process finished with exit code 0
*/ 

/*运行结果:
请输入整数:
10.1
输入的不是整数数据!
请输入小数:
小数数据:10.1

Process finished with exit code 0
*/
/*运行结果:
请输入整数:
48
整数数据:48
请输入小数:
12
小数数据:12.0

Process finished with exit code 0
*/
import java.util.Scanner;
public class Demo2022 {
    public static void main(String[] args) {
        //要求输入多个数字,并求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输出执行结果
        Scanner scanner = new Scanner(System.in);

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

        System.out.println("请输入数据");
        //通过循环判断是否还有输入,并在里面对每一次进行求和与统计
        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+"个数的平均值为:"+(sum/m));


        scanner.close();
    }
/*运行结果:
请输入数据
1
你输入了第1个数据,当前结果为:1.0
2
你输入了第2个数据,当前结果为:3.0
169
你输入了第3个数据,当前结果为:172.0
s
3个数的和为:172.0
3个数的平均值为:57.333333333333336

Process finished with exit code 0
*/

不对外输出值时,m++与++m一样

顺序结构

java的基本结构就是顺序结构,除非特别指明,否则就按照顺序一句一句执行

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

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

选择结构

if单选择结构

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

package com.struct;

import java.util.Scanner;

public class IfDemo {
    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

Process finished with exit code 0
*/

if双选择结构

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

package com.struct;
import java.util.Scanner;

public class IfDemo {
    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();
    }
}
/*运行结果:
请输入成绩
60
不及格

Process finished with exit code 0
*/

if多选择结构

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

package com.struct;

import java.util.Scanner;

public class IfDemo {
    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{
            System.out.println("成绩不合法");
        }

        scanner.close();
    }
}


/*运行结果:
请输入成绩
120
成绩不合法

Process finished with exit code 0
*/

注意:

if语句最多只有1个else语句,else语句在所有的else if语句之后。

if语句可以有若干个else if语句,他们必须在else语句之前。

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

嵌套的if结构

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

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

switch多选择结构

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

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

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

  • byte、short、int或者char

  • String(java se7开始switch开始支持字符串String类型),同时case标签必须为字符串常量或者字面量

  • package com.struct;
    
    public class SwitchDemo {
        public static void main(String[] args) {
            //case穿透   //switch匹配一个具体的值
            char grade = 'C';
    
            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("未知等级");
            }
        }
    }
    /*运行结果:
    及格
    
    Process finished with exit code 0
    */
    

循环结构

while循环

do…while循环

for循环

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

while循环

/*结构为:
while(布尔表达式){
  //循环内容
}
*/

只有布尔值为true,循环就会一直执行下去。

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

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

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

package com.struct;

public class WhileDemo {
    public static void main(String[] args) {
        //死循环
        while(true){
            //等待客户端连接
            //定时检查
            //......
        }
    }
}
========================================================
//计算1+2+3+...+100=?
package com.struct;

public class WhileDemo {
    public static void main(String[] args) {
        int i = 0;
        int sum = 0;
        while(i<100){
            i++;
            sum = i+sum;
        }
        System.out.println("总和结果为:"+sum);
    }
}
/*运行结果为:
总和结果为:5050

Process finished with exit code 0
*/

do…while循环

对于while语句而言,如果不满足条件,则不能进入循环。

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

语法:
do{
	//代码语句
}while(布尔表达式);
package com.struct;
//计算1+2+3+...+100=?
public class DoWhileDemo {
    public static void main(String[] args) {
        int i =0;
        int sum = 0;
        do {
            i++;
            sum = sum+i;
        }while(i<100);
        System.out.println(sum);
    }
}
/*运行结果:
5050

Process finished with exit code 0
*/

while和do…while的区别:

  • while先判断后执行。do…while是先执行后判断!

  • do…while总是保证循环体会被至少执行一次!(主要差别)

package com.struct;
//while和do...while的区别
public class DoWhileDemo {
    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

Process finished with exit code 0
*/

for循环

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

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

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

关于for循环有以下几点说明:

1.最先执行初始化步骤。可以声明一种类型,但可以初始化一个或多个循环控制变量,也可以是空语句。

2.然后,检测布尔表达式的值。如果为true,循环体被执行,如果为false,循环终止,开始执行循环体后面的语句。

3.执行一次循环后,更新循环控制变量(迭代因子控制循环变量的增减)。

4.再次检测布尔表达式。循环执行上面的过程。

for(  ;  ;  ){}    //死循环

练习1:计算0到100之间奇数和偶数的和

package com.struct;

public class ForDemo {
    public static void main(String[] args) {
        //练习1:计算0到100之间奇数和偶数的和
        int oddSum = 0;   //保存奇数的和
        int evenSum = 0;  //保存偶数的和

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

Process finished with exit code 0
*/

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

package com.struct;

public class ForDemo<or> {
    //练习2:用while或for循环输出1-1000之间能被5整除的数,并且每行输出3个
    public static void main(String[] args) {
        for (int i = 0; i <= 1000; i++) {
            if (i%5==0){
                System.out.print(i+"\t");
                //println输出完会换行
                //print输出完不会换行
            }
            if (i%(5*3)==0){
                System.out.println();
            }
        }
    }
}
/*运行结果:
0	
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	
Process finished with exit code 0
*/

练习3:打印九九乘法表

package com.struct;

public class ForDemo {
    public static void main(String[] args) {
        //练习3:打印九九乘法表

        //1.先打印第一列
        //2.把固定的1再用一个循环包起来
        //3.去掉重复项 i <= j;
        //4.调整样式

        for (int j = 1; j <= 9; j++) {
            for (int i = 1; i <= j; i++) {
                System.out.print(j+"*"+i+"="+(j*i)+"\t");
            }
            System.out.println();
        }
    }
}
/*运行结果:
1*1=1	
2*1=2	2*2=4	
3*1=3	3*2=6	3*3=9	
4*1=4	4*2=8	4*3=12	4*4=16	
5*1=5	5*2=10	5*3=15	5*4=20	5*5=25	
6*1=6	6*2=12	6*3=18	6*4=24	6*5=30	6*6=36	
7*1=7	7*2=14	7*3=21	7*4=28	7*5=35	7*6=42	7*7=49	
8*1=8	8*2=16	8*3=24	8*4=32	8*5=40	8*6=48	8*7=56	8*8=64	
9*1=9	9*2=18	9*3=27	9*4=36	9*5=45	9*6=54	9*7=63	9*8=72	9*9=81	

Process finished with exit code 0
*/
java增强for循环

java增强for循环语法格式如下:

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

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

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

package com.struct;

public class ForDemo {
    public static void main(String[] args) {
        int[] numbers = {10,20,30,40,50};  //定义了一个数组

        //遍历数组里的元素法1
        for (int i = 0;i<5;i++){
            System.out.println(numbers[i]);
        }
        System.out.println("==============");
        //遍历数组里的元素法2
        for (int x:numbers){
            System.out.println(x);
        }
    }
}
/*运行结果:
10
20
30
40
50
==============
10
20
30
40
50

Process finished with exit code 0
*/

break&continue

break:在任何循环语句的主体部分,均可用break控制循环的流程

break用于强行退出循环,不执行循环中剩余的语句。

​ (break语句也在switch语句中使用。)

package com.struct;

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");
    }
}
/*运行结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
123

Process finished with exit code 0
*/

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

可以理解为跳过此次操作!

package com.struct;

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);
        }
    }
}
/*运行结果:
123456789
111213141516171819
212223242526272829
313233343536373839
414243444546474849
515253545556575859
616263646566676869
717273747576777879
818283848586878889
919293949596979899

Process finished with exit code 0
*/

关于goto关键字:

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

package com.struct;

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+" ");
        }


    }
}
/*运行结果:
101 103 107 109 113 127 131 137 139 149 
Process finished with exit code 0
*/

卧槽:j < i / 2的妙在于:

j < i / 2是为了节约程序运行时间。

因为一个数如果不能以它本身的一半以内的数乘上另一个数得到,那么,它就是质数。

也就是说,一个数只可能被小于自己一半的数整除。

妙在少判断一半的数!!

练习

打印三角形

package com.struct;

public class TestTri {
    public static void main(String[] args) {
         //打印三角形
        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();

        }
    }
}

/*运行结果:
     + 
    +++ 
   +++++ 
  +++++++ 
 +++++++++ 

Process finished with exit code 0
*/

先i=1,然后执行下面3个for;

然后换行,i=2,继续执行下面3个for
参考视频:【狂神说Java】Java零基础学习视频通俗易懂

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值