JAVA基础 (三)

本文介绍了JAVA的基础流程控制,包括Scanner类获取用户输入、顺序结构、选择结构(if单选择、双选择、多选择、嵌套if和switch case)、循环结构(while、do while、for、增强for)以及break和continue的使用。详细讲解了各种结构的用法和实例,帮助读者掌握JAVA编程中的流程控制。
摘要由CSDN通过智能技术生成

流程控制

一、用户交换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、可以获得空白

练习1:使用next方式

package com.dudu.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()==true){
            //使用next方式接收
            String str = scanner.next();//程序会等待用户输入完毕
            System.out.println("输出的内容为:"+str);
        }

        //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
        scanner.close();
    }
}

练习2:使用nextLine方式

package com.dudu.scanner;

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方式接收:");
        if (scanner.hasNextLine()){
            String str = scanner.nextLine();
            System.out.println("输出的内容为:"+str);
        }
        scanner.close();
    }
}

练习3:

package com.dudu.scanner;

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.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();
    }
}

练习4:输入多个数字,并求其总和与平均数,每输入一个数字用回车键确认,通过输入非数字来结束输入并输出执行结果。

package com.dudu.scanner;

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()){
            double x = scanner.nextDouble();
            m = m + 1;
            sum = sum + x;
            System.out.println("你输入了第"+m+"个数据,然后当前结果sum="+sum);
        }
        System.out.println(m + "个数的和为" + sum);
        System.out.println(m + "个数的平均值是" + (sum/m));

        scanner.close();


    }
}

二、顺序结构

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

package com.dudu.struct;

public class ShunXuDemo {
    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语句来表示

package com.dudu.struct;

import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;

import java.util.Scanner;

public class IfDemo01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);//创建一个扫描器对象,用于接收键盘数据hello
        System.out.println("请输入内容:");
        String s = scanner.nextLine();//程序等待用户输入完毕
        //判断字符串是否相等
        if (s.equals("Hello")){
            System.out.println(s);
        }
        System.out.println("End");


        scanner.close();
    }
}

if双选择结构:

package com.dudu.struct;

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();
    }
}

if多选择结构:

if语句至多有1个else语句,else语句在所有的else if语句之后。
if语句可以有若干个else if语句,它们必须在else语句之前。
一旦其中一个else if语句检测为true,其他的else if以及else语句都将跳过执行。
package com.dudu.struct;

import java.util.Scanner;

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

        /*
        if语句至多有1个else语句,else语句在所有的else if语句之后。
        if语句可以有若干个else if语句,它们必须在else语句之前。
        一旦其中一个else if语句检测为true,其他的else if以及else语句都将跳过执行。
         */
        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<100 &&score>=80){
            System.out.println("B");
        }else if (score<100 && score>=70){
            System.out.println("C");
        }else if (score<100 && score>=60){
            System.out.println("D");
        }else if (score<60 && score>=0){
            System.out.println("不及格");
        }else{
            System.out.println("成绩不合法");
        }


        scanner.close();
    }
}

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

switch多选择结构:

多选择结构还有一个实现结构就是switch case语句。switch case语句判断一个变量与一系列值中某个值是否相等,每个值成为一个分支。switch语句中的变量类型可以是:

1、byte、short、int或char

2、从Java SE7开始

3、switch支持字符串String类型了

4、同时case标签必须为字符串常量或字面量

package com.dudu.struct;

public class SwitchDemo01 {
    public static void main(String[] args) {
        //case穿透
        char grade = 'B';

        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("未知等级");

四、循环结构

一、while循环

只要布尔表达式为true,循环就会一直执行下去。大多数情况是会让循环停止下来的,我们需要一个让表达式失效的方式来结束循环。少部分情况需要循环一直执行,比如服务器的请求响应监听等。循环条件为true就会造成无限循环(死循环),我们正常的业务编程中应该尽量避免死循环。会影响程序性能或者造成程序卡死崩溃。

package com.dudu.struct;

public class WhileDemo01 {
    public static void main(String[] args) {
        //输出1-100

        int i = 0;
        while (i<100){
            i++;
            System.out.println(i);
        }

    }
}

例题:计算1+2+3……+100

package com.dudu.struct;

public class WhileDemo02 {
    public static void main(String[] args) {
        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循环至少会执行一次。

while和do while的区别:

while先判断后执行,do while 总是先执行后判断。do while总是保证循环至少会被执行一次,这是它们的主要差别。

package com.dudu.struct;

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.dudu.struct;

public class DoWhileDemo02 {
    public static void main(String[] args) {
        int a = 0;
        while (a<0){
            System.out.println(a);
            a++;
        }//因为a=0,所以while循环不执行
        System.out.println("===========");
        do {
            System.out.println(a);
            a++;
        }while (a<0);//因为do while至少会执行一次,所以有输出结果
    }
}

二、For循环

虽然所有循环结构都可以用while循环或者do while循环表示,但java提供了另一种语句——for循环,使一些循环结构变得更加简单。**for循环语句是支持迭代的一种通用结构,是最有效、最灵活的循环结构。**for循环结构执行的次数是在执行前就确定的。

关于for循环几点说明:

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

package com.dudu.struct;

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 (int i = 1;i<=100;i++){
            System.out.println(i);
        }
        System.out.println("for循环结束!");


        
        }


    }
package com.dudu.struct;

public class ForDemo02 {
    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;

            }else {
                evensum+=i;
            }

        }
        System.out.println("奇数的和:"+oddsum);
        System.out.println("偶数的和:"+evensum);
    }
}

结果:奇数的和:2500

偶数的和:2550

package com.dudu.struct;

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

        }
    }
}

结果:5 10 15

20 25 30

35 40 45

…………

980 985 990

995 1000

package com.dudu.struct;

public class ForDemo04 {
    public static void main(String[] args) {
        //打印九九乘法表
        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();

        }




    }
}

结果:1x1=1

2x1=2 2x2=4

3x1=3 3x2=6 3x3=9

……………………

增强for循环:

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

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

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

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

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

package com.dudu.struct;

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用于强行退出循环,不执行循环中剩余的语句。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值