JavaSE笔记——02

发布时间 2023-04-24 22:26:10作者: 漫卿潇

Java流程控制

仅仅个人学习记录,不涉及任何商用

1.用户交互Scanner

从JDK 1.5 版本之后,专门提供了输入数据类Scanner,此类数据不但可以输入数据,而且也能方便地验证输入的数据。

->1. Scanner类概述

​ Scanner类可以接收任意的输入流。Scanner类放在java.util包中,其常用的方法如下表所示。在Scanner类中有一个可以接受InputStream类型的构造方法,这就表示只要是字节输入流的子类都可以通过Scanner类进行读取。

方法 类型 描述
public Scanner(File source) throws FileNotFoundException 构造 从文件中接收内容
public Scanner(InputStream source) 构造 从指定的字节输入流中接收内容
public boolean hasNext(Pattern pattern) 普通 判断输入数据是否符合指定的正则标准
public boolean hasNextInt() 普通 判断输入的数据是否是整数
public boolean hasNextFloat() 普通 判断输入的数据是否为小数
public String next() 普通 接收内容
public String next(Pattern pattern) 普通 接收内容,进行正则验证
public int nextInt() 普通 接收数字
public float nextFloat() 普通 接收小数
public Scanner useDelimiter(String pattern) 普通 设置读取的分隔符

->2.使用Scanner类

package Scanner;
import java.util.Scanner;

/**
 * @author Yu
 * @version 1.8
 * @since 1.0
 * 功能:(1)输入数据
 *       (2)使用方法hasNextXxx()进行输入数据验证
 */
public class Scanner01 {
    public static void main(String[] args) {
        // 1.创建一个扫描器对象,用于接收用户数据
        Scanner scan = new Scanner(System.in);
        System.out.println("使用next方式进行接收数据:");

        // 2.在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据
        if(scan.hasNext()){
            // 3.使用next方式接收
            String s = scan.next();
            System.out.println("接收的内容为:"+s);
        }
        // 4.凡是属于IO流的类如果不关闭会一直占用资源,要养成良好习惯用完就关掉它
        scan.close();
    }
}
package Scanner;
import java.util.Scanner;

/**
 * @author Yu
 * @version 1.8
 * @since 1.0
 * 功能:(1)输入数据
 *       (2)使用方法hasNextXxx()进行输入数据验证
 */
public class Scanner02 {
    public static void main(String[] args) {
        // 1.创建一个扫描器对象,用于接收用户数据
        Scanner scan = new Scanner(System.in);
        System.out.println("使用nextLine方式进行接收数据:");

        // 2.在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据
        if(scan.hasNext()){
            // 3.使用next方式接收
            String s = scan.nextLine();
            System.out.println("接收的内容为:"+s);
        }
        // 4.凡是属于IO流的类如果不关闭会一直占用资源,要养成良好习惯用完就关掉它
        scan.close();
    }
}

总结:

  • next () :

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

    1. Enter作为结束符,即返回输入回车之前所有的字符
    2. nextLine()可以获取空白
package Scanner;
import java.util.Scanner;

/**
 * @author Yu
 * @version 1.8
 * @since 1.0
 * 功能:(1)输入数据
 *       (2)使用方法hasNextXxx()进行输入数据验证
 *       (3)we can input more than one number to do sum and adv,and if we input not number can output sum and adv.
 */
public class Scanner03 {
    public static void main(String[] args) {
        // 1.创建一个扫描器对象,用于接收用户数据
        Scanner scanner = new Scanner(System.in);
        // 2.定义局部变量
        double sum = 0;
        int num = 0;
        // 3.通过循环,不断地去判断是否有下一个输入数据,同时接收数据
        while (scanner.hasNextDouble()){
            double x = scanner.nextDouble();
            num++;
            sum += x;
        }
        System.out.println("sum:"+sum);
        System.out.println("adv:"+sum/num);
    }
}

package Scanner;
import java.util.Scanner;

/**
 * @author Yu
 * @version 1.8
 * @since 1.0
 * 功能:(1)输入数据
 *       (2)使用方法hasNextXxx()进行输入数据验证
 *       (3)java 判断输入的字符串是否符合要求,不符合就重复输入
 */
public class Scanner04 {
    public static void main(String[] args) {
        System.out.println("请输入整数:");
        Boolean flag = true;

        // 1.通过循环,直到输入的字符串符合要求,就跳出循环
        while (flag) {
            // 2.创建一个扫描器对象,用于接收用户数据
            Scanner scanner = new Scanner(System.in);
            // 3.判断输入是否为整数,是就用nextInt()方式进行接收并打印;否则不接受,重新输入!!!
            if(scanner.hasNextInt()){
                int i = scanner.nextInt();
                scanner.close();
                System.out.println("输入的整数为:"+i);
                flag=false; //也可以直接用 break 跳出
            }else {
                System.out.println("请重新输入!!");
            }
        }

    }

}

package Scanner;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/**
 * @author Yu
 * @version 1.8
 * @since 2.0
 * 功能:(1)输入数据
 *       (2)使用正则表达式获取日期
 *       (3)匹配时间:2021/05/24  年份没什么限制,月份 1-12 月,日期1-31;
 *       年份 :\d{4}  月份: 1[0,1,2]|0?\d   日期: 3[0,1]|[1,2]\d|0?\d
 */
public class ScannerTime01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = null;
        Date date = null;
        System.out.println("输入日期(yyyy-MM-dd):");

        if (scanner.hasNext("(\\d{4})[-/](1[0,1,2]|0?\\d)[-/](3[0,1]|[1,2]\\d|0?\\d)")){
            str = scanner.next("(\\d{4})[-/](1[0,1,2]|0?\\d)[-/](3[0,1]|[1,2]\\d|0?\\d)");
            try {
                date = new SimpleDateFormat("yyyy-MM-dd").parse(str);
                scanner.close();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("输入的日期格式错误!");
        }
        System.out.println(date);
        System.out.println(str);
    }
}

总结:

  1. 正则表达式相关概率请参考菜鸟教程

    [https://www.runoob.com/regexp/regexp-tutorial.html]:

  2. /*验证日期是yyyy-MM-dd支持闰年的正则表达式*/
    "((\\d{2}(([02468][048])|([13579][26]))[\\-]((((0?[13578])|(1[02]))[\\-]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-]((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-]((((0?[13578])|(1[02]))[\\-]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-]((0?[1-9])|(1[0-9])|(2[0-8]))))))"
    
    /*验证日期是yyyy-MM-dd HH:mm:ss支持闰年的正则表达式*/
        "((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s((([0-1][0-9])|(2?[0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))"
        
    /*为空的验证*/
        "\\s*"
    

->3.扩展正则表达式在java中的应用

package Regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Yu
 * @version 1.8
 * @since 1.0
 * 功能:(1)字符串的查找操作:Pattern和Matcher
 *      (2)字符串匹配操作:可以使用字符串的matchers方法
 *      (3)字符串的替换操作:字符串的replaceAll()和replaceFirst()方法
 *      (4)字符串的分割:字符串的split()方法
 */
public class Regex01 {
    public static void main(String[] args) {
        String regex = "\\w{3,}";
        String s = "abcd123";
        // 1.两者均用于检测字符串是否匹配给定的正则表达式
        System.out.println(s.matches(regex));
        System.out.println(Pattern.matches(regex,s));

        /* 2.replaceAll()方法是使用给定的参数 replacement 替换字符串所有匹配给定的正则表达式的字符串
        语法:
        public String replaceAll(String regex, String replacement)
        参数
        regex -- 匹配此字符串的正则表达式。
        newChar -- 用来替换每个匹配项的字符串。
        返回值
        成功则返回替换的字符串,失败则返回原始字符串。
        */
        String Str = new String("www.google.com");
        System.out.print("匹配成功返回值 :" );
        System.out.println(Str.replaceAll("(.*)google(.*)", "runoob" ));
        System.out.print("匹配失败返回值 :" );
        System.out.println(Str.replaceAll("(.*)taobao(.*)", "runoob" ));

        /*
        * replaceFirst() 方法使用给定的参数 replacement 替换字符串第一个匹配给定的正则表达式的子字符串。
        语法
        public String replaceFirst(String regex,String replacement)
        参数
        regex -- 匹配此字符串的正则表达式。
        replacement -- 用来替换第一个匹配项的字符串。
        返回值
        成功则返回替换的字符串,失败则返回原始字符串。
        */
        Str = new String("hello runoob,I am from runoob。");
        System.out.print("返回值 :" );
        System.out.println(Str.replaceFirst("runoob", "google" ));
        System.out.print("返回值 :" );
        System.out.println(Str.replaceFirst("(.*)runoob(.*)", "google" ));

        regex = "\\w{3,7}";
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher("abcd123aaaa112321dddd333");
//        System.out.println(matcher.matches());
        System.out.println(matcher.find());
        System.out.println(matcher.end());
        System.out.println(matcher.group());

        System.out.println(matcher.find());
        System.out.println(matcher.end());
        System.out.println(matcher.group());

    }

}

  • 正则表达式的验证网址:

2.顺序结构

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

3.选择结构

  • if单选择结构 if( )

  • if双选择结构 if( ){ }else

  • if多选择结构 if( ){ }else if{ }else{}

  • 嵌套的if结构 if( )

    package Srbcut;
    import java.util.Scanner;
    /**
    
     * @author Yu
     * @version 1.8
     * @since 1.0
     * 功能:(1)输入数据
     * (2)判断学生成绩等级
        */
       public class Srbcut01 {
       public static void main(String[] args) {
           Scanner scanner = new Scanner(System.in);
           double grade = 0;
           grade = scanner.nextDouble();
           if(grade==100){
                System.out.println("满分");
            }else if (grade<100 && grade>90){
                System.out.println("A");
            }else if (grade<90 && grade>80){
                System.out.println("B");
            }else if (grade<80 && grade>70){
                System.out.println("C");
            }else if (grade<70 && grade>60){
                System.out.println("D");
            }else if (grade<60 && grade>0){
                System.out.println("不及格");
            }else{
                System.out.println("输入不合法");
            }
            scanner.close();
       }
    }
    

4.Switch语句

char grade = 'C'; //JDK新特性 可以是字符串(字符本质还是数字)
switch (grade){
  case 'A':
      System.out.println("优秀");
      break; //可选,跳出当前结构
  case 'B':
      System.out.println("良好");
      break;
  case 'C':
      System.out.println("合格");
      break;
  default: //默认,以上值没匹配到
      System.out.println("不及格");
      break;
}

在这里插入图片描述

5.循环结构

  • while循环

  • do……while循环

  • for 循环

  • package Srbcut;
    
    public class While {
        public static void main(String[] args) {
            int i = 0;
            int sum = 0;
            while(i<100){
                i++;
                sum+=i;
    
            }
            System.out.println(sum);
        }
    }
    
  • package Srbcut;
    
    public class DoWhile {
        public static void main(String[] args) {
            int a = 0;
            while (a<0){
                System.out.println(a);
            }
            do {
                System.out.println(a);
            }while (a<0);
        }
    }
    
  • package Srbcut;
    
    public class ForDemo01 {
        public static void main(String[] args){
            //输出0-1000之间,能被5整除的数,并且每行输出3个值
            for(int i=0;i<=1000;i++){
                if(i%5==0){
                    System.out.print(i+"\t");
                }
                if(i%(5*3)==0){
                    System.out.println();
                }
            }
        }
    }
    
  • package Srbcut;
    
    public class ForDemo01 {
        public static void main(String[] args){
            //99cfabiao
            int sum = 0;
            for(int i=1;i<=9;i++){
                for (int j=1; j<=i;j++){
                    sum = i*j;
                    System.out.print(j+"*"+i+"="+sum+"\t");
                }
                System.out.println();
            }
        }
    }
    
  • package Srbcut;
    
    public class ForDemo01 {
        public static void main(String[] args){
            int[] number={30,40,50,60,70};     //定义一个数组
            for(int i = 0; i<5; i++){
                System.out.println(number[i]);
            }
            System.out.println("======================");
            for (int x:number){
                System.out.println(x);
            }
        }
    }
    

7.break & continue

  • break可用在任何循环的主体部分,由于强行退出循环,也可以用在switch语句。

  • continue用于循环语句中,终止某次循环过程,跳过剩余语句,之间进行下一次循环条件判断。

  • 带标签的continue:后面跟一个冒号的标识符 label:

  • package Srbcut;
    /**
     * @author Yu
     * @version 1.8
     * @since 1.0
     * 功能:(1)打印0-150之间所有的质数
     */
    public class Continue01 {
        public static void main(String[] args) {
            int count = 0;
            outer:for (int i=0;i<=150;i++){
                for (int j=2;j<i/2;j++){
                    if(i%j==0){
                        continue outer;
                    }
                }
                System.out.println(i);
            }
        }
    }
    
    
  • package Srbcut;
    /**
     * @author Yu
     * @version 1.8
     * @since 1.0
     * 功能:(1)打印0-150之间所有的质数
     */
    public class Continue01 {
        public static void main(String[] args) {
            int count = 0;
            outer:for (int i=0;i<=150;i++){
                for (int j=2;j<i/2;j++){
                    if(i%j==0){
                        continue outer;
                    }
                }
                System.out.println(i);
            }
        }
    }