d14-2-Common API02

1. Time Date Class

1.1 Date class (application)

  • Time Origin in Computer

    January 1, 1970, 00:00:00

  • Time Conversion Units

    1 second = 1000 milliseconds

  • An overview of the Date class

    Date represents a specific time, accurate to milliseconds

  • Date class construction method

    Method Name Explain
    public Date() Assign a Date object and initialize it so that it represents the time it was allocated, accurate to milliseconds
    public Date(long date) Assign a Date object and initialize it to represent the number of milliseconds specified from standard base time
  • Sample Code

    public class DateDemo01 {
        public static void main(String[] args) {
            //public Date(): Assign a Date object and initialize it so that it represents the time it was allocated, accurate to milliseconds
            Date d1 = new Date();
            System.out.println(d1);
    
            //public Date(long date): Assign a Date object and initialize it to represent the number of milliseconds specified from standard base time
            long date = 1000*60*60;
            Date d2 = new Date(date);
            System.out.println(d2);
        }
    }
    

1.2 Date Class Common Methods (Applications)

  • common method

    Method Name Explain
    public long getTime() Gets the millisecond value of the date object from 00:00:00 on January 1, 1970 to the present
    public void setTime(long time) Set the time, given the value in milliseconds
  • Sample Code

    public class DateDemo02 {
        public static void main(String[] args) {
            //Create Date object
            Date d = new Date();
    
            //public long getTime(): Gets the millisecond value of the date object from 00:00:00 on January 1, 1970 to the present
    //        System.out.println(d.getTime());
    //        System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "year");
    
            //public void setTime(long time): Set the time, given a value of milliseconds
    //        long time = 1000*60*60;
            long time = System.currentTimeMillis();
            d.setTime(time);
    
            System.out.println(d);
        }
    }
    

1.3 SimpleDateFormat class (application)

  • An overview of the SimpleDateFormat class

    ( SimpleDateFormat is a specific class for locale-sensitive formatting and parsing dates.

    ( We focus on formatting and parsing dates

  • SimpleDateFormat class construction method

    Method Name Explain
    public SimpleDateFormat() Construct a SimpleDateFormat using default mode and date format
    public SimpleDateFormat(String pattern) Construct a SimpleDateFormat to use the given pattern and default date format
  • Common methods of the SimpleDateFormat class

    • Formatting (from Date to String)
      • public final String format(Date date): Format the date into a date/time string
    • Parse (from String to Date)
      • public Date parse(String source): parses text from the beginning of a given string to generate a date
  • Sample Code

    public class SimpleDateFormatDemo {
        public static void main(String[] args) throws ParseException {
            //Formatting: From Date to String
            Date d = new Date();
    //        SimpleDateFormat sdf = new SimpleDateFormat();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
            String s = sdf.format(d);
            System.out.println(s);
            System.out.println("--------");
    
            //From String to Date
            String ss = "2048-08-09 11:11:11";
            //ParseException
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dd = sdf2.parse(ss);
            System.out.println(dd);
        }
    }
    

1.4 Time and Date Exercises (Applications)

  • demand

    Secondary killing starts at 00:00:00 on November 11, 2020, ends at 00:10:00 on November 11, 2020, orders placed by user Xiaojia at 00:03:47 on November 11, 2020, and orders placed by user Xiaojia at 00:10:11 on November 11, 2020. Determine whether users have successfully participated in secondhand killing activities

  • Implementation Steps

    1. Determine if the time of placing an order is within the range from start to end
    2. Turn time as a string into milliseconds
  • code implementation

    public class DateDemo5 {
        public static void main(String[] args) throws ParseException {
            //Start time: 10:0:0 on November 11, 2020
            //End time: 10:10:0 November 11, 2020
    
            //Xiaojia November 11, 2020 0:03:47
            //Peels 10:10:11 November 2020
    
            //1. It is OK to judge if the order time of the two students is within the range.
    
            //2. Convert every time into milliseconds.
    
            String start = "2020 10 November 11, 1:0:0";
            String end = "2020 10 November 11, 1:10:0";
    
            String jia = "2020 10 November 11, 1:03:47";
            String pi = "2020 10 November 11, 1:10:11";
    
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
            long startTime = sdf.parse(start).getTime();
            long endTime = sdf.parse(end).getTime();
    
    //        System.out.println(startTime);
    //        System.out.println(endTime);
            long jiaTime = sdf.parse(jia).getTime();
            long piTime = sdf.parse(pi).getTime();
    
            if(jiaTime >= startTime && jiaTime <= endTime){
                System.out.println("Xiao Jia took part in the seconds killing activity");
            }else{
                System.out.println("Xiao Jia did not participate in last second killing activity");
            }
    
            System.out.println("------------------------");
    
            if(piTime >= startTime && piTime <= endTime){
                System.out.println("Little Pi took part in the seconds killing activity");
            }else{
                System.out.println("Little Pi didn't participate in last-second killing");
            }
    
        }
      
    }
    

2.JDK8 Time Date Class

2.1 JDK8 New Date Class (Understanding)

  • LocalDate represents the date (year, month, day)
  • LocalTime represents time (minutes and seconds)
  • LocalDateTime represents time + date (year, month, day, hour, second)

2.2 LocalDateTime creation method (application)

  • Method Description

    Method Name Explain
    public static LocalDateTime now() Get the current system time
    Public static Local DateTime of (year, month, day, hour, minute, second) Initializes a LocalDateTime object with the specified year, month, day, time, minute, and second
  • Sample Code

    public class JDK8DateDemo2 {
        public static void main(String[] args) {
            LocalDateTime now = LocalDateTime.now();
            System.out.println(now);
    
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 11);
            System.out.println(localDateTime);
        }
    }
    

2.3 LocalDateTime acquisition method (application)

  • Method Description

    Method Name Explain
    public int getYear() Acquire Year
    public int getMonthValue() Get month (1-12)
    public int getDayOfMonth() Get the day of the month (1-31)
    public int getDayOfYear() Get the day of the year (1-366)
    public DayOfWeek getDayOfWeek() Get Weeks
    public int getMinute() Get Minutes
    public int getHour() Get Hours
  • Sample Code

    public class JDK8DateDemo3 {
        public static void main(String[] args) {
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 20);
            //public int getYear() Get Year
            int year = localDateTime.getYear();
            System.out.println("Year is" +year);
            //public int getMonthValue() get month (1-12)
            int month = localDateTime.getMonthValue();
            System.out.println("Month is" + month);
    
            Month month1 = localDateTime.getMonth();
    //        System.out.println(month1);
    
            //public int getDayOfMonth() Gets the day of the month (1-31)
            int day = localDateTime.getDayOfMonth();
            System.out.println("Date is" + day);
    
            //public int getDayOfYear() Gets the day of the year (1-366)
            int dayOfYear = localDateTime.getDayOfYear();
            System.out.println("This is the first of the year" + dayOfYear + "day");
    
            //public DayOfWeek getDayOfWeek() Get Week
            DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
            System.out.println("Weekday" + dayOfWeek);
    
            //public int getMinute() to get minutes
            int minute = localDateTime.getMinute();
            System.out.println("Minutes are" + minute);
            //public int getHour() get hours
      
            int hour = localDateTime.getHour();
            System.out.println("Hours are" + hour);
        }
    }
    

2.4 LocalDateTime conversion method (application)

  • Method Description

    Method Name Explain
    public LocalDate toLocalDate () Convert to a LocalDate object
    public LocalTime toLocalTime () Convert to a LocalTime object
  • Sample Code

    public class JDK8DateDemo4 {
        public static void main(String[] args) {
            LocalDateTime localDateTime = LocalDateTime.of(2020, 12, 12, 8, 10, 12);
            //Public LocalDate to LocalDate () converted to a LocalDate object
            LocalDate localDate = localDateTime.toLocalDate();
            System.out.println(localDate);
    
            //Public LocalTime to LocalTime () is converted to a LocalTime object
            LocalTime localTime = localDateTime.toLocalTime();
            System.out.println(localTime);
        }
    }
    

2.5 LocalDateTime Formatting and Parsing (Application)

  • Method Description

    Method Name Explain
    public String format (specified format) Format a LocalDateTime into a string
    public LocalDateTime parse (Ready to parse string, parse format) Parse a date string into a LocalDateTime object
    public static DateTimeFormatter ofPattern(String pattern) Gets a date formatter DateTimeFormatter object using the specified date template
  • Sample Code

    public class JDK8DateDemo5 {
        public static void main(String[] args) {
            //method1();
            //method2();
        }
    
        private static void method2() {
            //public static LocalDateTime parse parses a date string into a LocalDateTime object
            String s = "2020 13 November 12, 1:14:15";
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy year MM month dd day HH:mm:ss");
            LocalDateTime parse = LocalDateTime.parse(s, pattern);
            System.out.println(parse);
        }
    
        private static void method1() {
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 12, 13, 14, 15);
            System.out.println(localDateTime);
            //public String format formats a LocalDateTime into a string
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy year MM month dd day HH:mm:ss");
            String s = localDateTime.format(pattern);
            System.out.println(s);
        }
    }
    

2.6 LocalDateTime Increase or Decrease Time Approach (Application)

  • Method Description

    Method Name Explain
    public LocalDateTime plusYears (long years) Add or subtract last year
    public LocalDateTime plusMonths(long months) Add or subtract months
    public LocalDateTime plusDays(long days) Add or subtract days
    public LocalDateTime plusHours(long hours) When adding or subtracting
    public LocalDateTime plusMinutes(long minutes) Add or subtract points
    public LocalDateTime plusSeconds(long seconds) Add or subtract seconds
    public LocalDateTime plusWeeks(long weeks) Add or subtract weeks
  • Sample Code

    /**
     * JDK8 Method of adding or subtracting time from time class
     */
    public class JDK8DateDemo6 {
        public static void main(String[] args) {
            //Public Local DateTime plusYears added or subtracted from last year
    
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
            //LocalDateTime newLocalDateTime = localDateTime.plusYears(1);
            //System.out.println(newLocalDateTime);
    
            LocalDateTime newLocalDateTime = localDateTime.plusYears(-1);
            System.out.println(newLocalDateTime);
        }
    }
    

2.7 LocalDateTime Reduction or Increase Time Method (Application)

  • Method Description

    Method Name Explain
    public LocalDateTime minusYears (long years) Subtract or add years
    public LocalDateTime minusMonths(long months) Subtract or add months
    public LocalDateTime minusDays(long days) Subtract or add days
    public LocalDateTime minusHours(long hours) When subtracting or adding
    public LocalDateTime minusMinutes(long minutes) Minus or add points
    public LocalDateTime minusSeconds(long seconds) Subtract or add seconds
    public LocalDateTime minusWeeks(long weeks) Subtract or add weeks
  • Sample Code

    /**
     * JDK8 Method of reducing or adding time to a time class
     */
    public class JDK8DateDemo7 {
        public static void main(String[] args) {
            //Public Local DateTime minus Years (long years) minus or add years
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
            //LocalDateTime newLocalDateTime = localDateTime.minusYears(1);
            //System.out.println(newLocalDateTime);
    
            LocalDateTime newLocalDateTime = localDateTime.minusYears(-1);
            System.out.println(newLocalDateTime);
    
        }
    }
    

2.8 LocalDateTime Modification Method (Application)

  • Method Description

    Method Name Explain
    public LocalDateTime withYear(int year) Direct modification year
    public LocalDateTime withMonth(int month) Modify Month Directly
    public LocalDateTime withDayOfMonth(int dayofmonth) Direct modification date (the day of the month)
    public LocalDateTime withDayOfYear(int dayOfYear) Direct modification date (day of year)
    public LocalDateTime withHour(int hour) Modify hours directly
    public LocalDateTime withMinute(int minute) Modify minutes directly
    public LocalDateTime withSecond(int second) Modify seconds directly
  • Sample Code

    /**
     * JDK8 Time class modification time
     */
    public class JDK8DateDemo8 {
        public static void main(String[] args) {
            //Public Local DateTime with Year (int year) Modified Year
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
           // LocalDateTime newLocalDateTime = localDateTime.withYear(2048);
           // System.out.println(newLocalDateTime);
    
            LocalDateTime newLocalDateTime = localDateTime.withMonth(20);
            System.out.println(newLocalDateTime);
    
        }
    }
    

2.9 Period (Application)

  • Method Description

    Method Name Explain
    Public static Period between (start time, end time) Calculate the interval between two "times"
    public int getYears() Number of years to get this time
    public int getMonths() Get the total number of months for this period
    public int getDays() Get days for this period
    public long toTotalMonths() Get the total number of months for this period
  • Sample Code

    /**
     *  Calculate the interval between two times
     */
    public class JDK8DateDemo9 {
        public static void main(String[] args) {
            //Public static Period between (start time, end time) calculates the interval between two "times"
    
            LocalDate localDate1 = LocalDate.of(2020, 1, 1);
            LocalDate localDate2 = LocalDate.of(2048, 12, 12);
            Period period = Period.between(localDate1, localDate2);
            System.out.println(period);//P28Y11M11D
    
            //public int getYears() gets the number of years of this time
            System.out.println(period.getYears());//28
            //public int getMonths() gets the number of months for this period
            System.out.println(period.getMonths());//11
            //public int getDays() gets days for this period
            System.out.println(period.getDays());//11
    
            //Public long to TotalMonths() to get the total number of months during this period
            System.out.println(period.toTotalMonths());//347
    
        }
    }
    

2.10 Duration (Application)

  • Method Description

    Method Name Explain
    Public static Durationbetween (start time, end time) Calculate the interval between two "times"
    public long toSeconds() Get seconds at this interval
    public int toMillis() Get milliseconds of this time interval
    public int toNanos() Get the nanoseconds of this time interval
  • Sample Code

    /**
     *  Calculate the interval between two times
     */
    public class JDK8DateDemo10 {
        public static void main(String[] args) {
            //Public static Duration between (start time, end time) calculates the interval between two "times"
    
            LocalDateTime localDateTime1 = LocalDateTime.of(2020, 1, 1, 13, 14, 15);
            LocalDateTime localDateTime2 = LocalDateTime.of(2020, 1, 2, 11, 12, 13);
            Duration duration = Duration.between(localDateTime1, localDateTime2);
            System.out.println(duration);//PT21H57M58S
            //public long toSeconds() 	        Get seconds at this interval
            System.out.println(duration.toSeconds());//79078
            //public int toMillis() 	            Get milliseconds of this time interval
            System.out.println(duration.toMillis());//79078000
            //public int toNanos() gets nanoseconds of this time interval
            System.out.println(duration.toNanos());//79078000000000
        }
    }
    

3. Exceptions

3.1 Anomalies (Memory)

  • Overview of anomalies

    ( An exception is a malfunction in the program

  • Abnormal Architecture

3.2 Difference between compile-time and run-time exceptions (memory)

  • Compile-time exceptions

    • Are Exception classes and their subclasses
    • Processing must be displayed or the program will fail to compile
  • Runtime Exceptions

    • Are both RuntimeException classes and their subclasses
    • No display handling is required or can be handled as an exception during compilation
  • Diagram

3.3 How the JVM handles exceptions by default (understand)

  • If something goes wrong with the program and we don't do anything, the JVM will do it by default in two steps:
    • Information such as the name of the exception, the cause of the error and the location of the exception is output to the console
    • Program Stop Execution

3.4 View exception information (understanding)

When the console prints the exception information, it prints the exception class name, the reason for the exception, and the location of the exception

When we adjust a bug, we can find the location of the exception, analyze the cause, and modify the exception code according to the prompt

3.5 throws handling exceptions (application)

  • Define Format

    public void Method() throws Exception Class Name {
        
    }
    
  • Sample Code

    public class ExceptionDemo {
        public static void main(String[] args) throws ParseException{
            System.out.println("start");
    //        method();
              method2();
    
            System.out.println("End");
        }
    
        //Compile-time exceptions
        public static void method2() throws ParseException {
            String s = "2048-08-09";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date d = sdf.parse(s);
            System.out.println(d);
        }
    
        //Runtime Exceptions
        public static void method() throws ArrayIndexOutOfBoundsException {
            int[] arr = {1, 2, 3};
            System.out.println(arr[3]);
        }
    }
    
  • Matters needing attention

    • This throws format follows the parentheses of the method
    • Compile-time exceptions must be handled by either try...catch...
    • Runtime exceptions are not written after methods because they occur only at runtime. Runtime exceptions are handled by jvm by default

3.6 throw throws an exception (apply)

  • format

    throw new exception ();

  • Be careful

    This format is within a method, indicating that the current code manually throws an exception, and the following code is no longer executed

  • Differences between throws and throws

    throws throw
    Used after method declarations, followed by exception class names Used within a method body, followed by an exception object name
    Indicates a declared exception, which may occur when the method is called Indicates that an exception object is thrown manually and handled by a statement within the method body
  • Sample Code

    public class ExceptionDemo8 {
        public static void main(String[] args) {
            //int [] arr = {1,2,3,4,5};
            int [] arr = null;
            printArr(arr);//You will receive an exception.
                            //We need to handle the exception ourselves.
        }
    
        private static void printArr(int[] arr) {
            if(arr == null){
                //Did the caller know that the print was successful?
                //System.out.println("parameter cannot be null");
                throw new NullPointerException(); //When the parameter is null
                                                //An exception object was manually created, thrown to the caller, and an exception was generated
            }else{
                for (int i = 0; i < arr.length; i++) {
                    System.out.println(arr[i]);
                }
            }
        }
    
    }
    

3.7 try-catch handling exceptions (application)

  • Define Format

    try {
    	Code with possible exceptions;
    } catch(Exception Class Name Variable Name) {
    	Handling code for exceptions;
    }
    
  • Execute process

    • The program starts with code inside the try
    • If an exception occurs, it jumps to the corresponding catch to execute
    • After execution, the program can continue
  • Sample Code

    public class ExceptionDemo01 {
        public static void main(String[] args) {
            System.out.println("start");
            method();
            System.out.println("End");
        }
    
        public static void method() {
            try {
                int[] arr = {1, 2, 3};
                System.out.println(arr[3]);
                System.out.println("Is it accessible here");
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("The array index you accessed does not exist. Please go back and modify it to the correct index");
            }
        }
    }
    
  • Be careful

    1. If there is no problem in try, how do I do it?

      All the code in the try is executed, not the code in the catch

    2. If you encounter problems in try, will the code below try execute again?

      Then jump directly to the corresponding catch statement and the code below try will no longer execute
      When all the statements in the catch are executed, the whole system is executed completely. Continue with the following code

    3. If the problem is not captured, how does the program run?

      Then try...catch is equivalent to not writing. That is, it is not handled by itself.
      Deliver to virtual machine by default.

    4. What to do if there are several exceptions that may occur at the same time?

      If there are multiple exceptions, then you can write multiple catch es.
      Note: If there is a child-parent relationship between multiple exceptions, the parent must be written below

3.8 Throwable member method (application)

  • common method

    Method Name Explain
    public String getMessage() Returns the detailed message string for this throwable
    public String toString() Return this throwable short description
    public void printStackTrace() Output exception error information to console
  • Sample Code

    public class ExceptionDemo02 {
        public static void main(String[] args) {
            System.out.println("start");
            method();
            System.out.println("End");
        }
    
        public static void method() {
            try {
                int[] arr = {1, 2, 3};
                System.out.println(arr[3]); //new ArrayIndexOutOfBoundsException();
                System.out.println("Is it accessible here");
            } catch (ArrayIndexOutOfBoundsException e) { //new ArrayIndexOutOfBoundsException();
    //            e.printStackTrace();
    
                //public String getMessage(): Returns the detailed message string for this throwable
    //            System.out.println(e.getMessage());
                //Index 3 out of bounds for length 3
    
                //public String toString(): Returns this short description that can be thrown
    //            System.out.println(e.toString());
                //java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    
                //public void printStackTrace(): Output exception error information to console
                e.printStackTrace();
    //            java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    //            at com.itheima_02.ExceptionDemo02.method(ExceptionDemo02.java:18)
    //            at com.itheima_02.ExceptionDemo02.main(ExceptionDemo02.java:11)
    
            }
        }
    }
    

3.9 Exceptional Practice (Application)

  • demand

    Keyboard records the names and ages of the students, aged 18 - 25, beyond which abnormal data cannot be assigned. It needs to be re-entered until it is correct

  • Implementation Steps

    1. Create Student Object
    2. Enter names and ages on the keyboard and assign them to students
    3. Enter again if illegal data
  • code implementation

    Student Class

    public class Student {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            if(age >= 18 && age <= 25){
                this.age = age;
            }else{
                //An exception occurs when age is not valid
                throw new RuntimeException("Age out of range");
            }
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    

    Test Class

    public class ExceptionDemo12 {
        public static void main(String[] args) {
            // Keyboard records the names and ages of students aged 18 - 25 years.
            // Beyond this range, the exception data cannot be assigned. It needs to be re-entered until it is correct.
    
            Student s = new Student();
    
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter your name");
            String name = sc.nextLine();
            s.setName(name);
           while(true){
               System.out.println("Please enter your age");
               String ageStr = sc.nextLine();
               try {
                   int age = Integer.parseInt(ageStr);
                   s.setAge(age);
                   break;
               } catch (NumberFormatException e) {
                   System.out.println("Please enter an integer");
                   continue;
               } catch (AgeOutOfBoundsException e) {
                   System.out.println(e.toString());
                   System.out.println("Please enter a range age");
                   continue;
               }
               /*if(age >= 18 && age <=25){
                   s.setAge(age);
                   break;
               }else{
                   System.out.println("Please enter the required age ";
                   continue;
               }*/
           }
            System.out.println(s);
    
        }
    }
    

3.10 Custom Exceptions (Apply)

  • Overview of custom exceptions

    We can customize exceptions when the exceptions provided in Java do not meet our needs

  • Implementation Steps

    1. Define exception classes
    2. Write Inheritance Relation
    3. Provide empty parameter construction
    4. Provide parametric constructs
  • code implementation

    Exception Class

    public class AgeOutOfBoundsException extends RuntimeException {
        public AgeOutOfBoundsException() {
        }
    
        public AgeOutOfBoundsException(String message) {
            super(message);
        }
    }
    

    Student Class

    public class Student {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            if(age >= 18 && age <= 25){
                this.age = age;
            }else{
                //If the exceptions provided in Java do not meet our needs, we can use custom exceptions
                throw new AgeOutOfBoundsException("Age out of range");
            }
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    

    Test Class

    public class ExceptionDemo12 {
        public static void main(String[] args) {
            // Keyboard records the names and ages of students aged 18 - 25 years.
            // Beyond this range, the exception data cannot be assigned. It needs to be re-entered until it is correct.
    
            Student s = new Student();
    
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter your name");
            String name = sc.nextLine();
            s.setName(name);
           while(true){
               System.out.println("Please enter your age");
               String ageStr = sc.nextLine();
               try {
                   int age = Integer.parseInt(ageStr);
                   s.setAge(age);
                   break;
               } catch (NumberFormatException e) {
                   System.out.println("Please enter an integer");
                   continue;
               } catch (AgeOutOfBoundsException e) {
                   System.out.println(e.toString());
                   System.out.println("Please enter a range age");
                   continue;
               }
               /*if(age >= 18 && age <=25){
                   s.setAge(age);
                   break;
               }else{
                   System.out.println("Please enter the required age ";
                   continue;
               }*/
           }
            System.out.println(s);
    
        }
    }
    

4.Optional

4.1 Get Objects (Application)

  • Overview of Optional

    Container objects that may or may not contain non-null values

  • Method introduction

    Method Name Explain
    static Optional of(T value) Gets an Optional object that encapsulates an object with a non-null value
    static Optional ofNullable(T value) Gets an Optional object, Optional encapsulated value object can be null or not
  • Sample Code

    public class OptionalDemo1 {
        public static void main(String[] args) {
            //method1();
    
            //public static <T> Optional<T> ofNullable(T value)
            //Gets an Optional object, Optional encapsulated value object can be null or not
            //Student s = new Student("zhangsan",23);
            Student s = null;
            //The ofNullable method, which encapsulates either null or not.
            Optional<Student> optional = Optional.ofNullable(s);
    
            System.out.println(optional);
        }
    
        private static void method1() {
            //Static <T> Optional <T> of (T value) Gets an Optional object encapsulating an object with a non-null value
    
            //Student s = new Student("zhangsan",23);
            Student s = null;
            //Optional can be seen as a container containing an object that references a data type.
            //The return value is the object of Optional
            //If the of f method is used, the encapsulated object will throw a null pointer exception if it is empty
            Optional<Student> optional1 = Optional.of(s);
            System.out.println(optional1);
        }
    }
    

4.2 Common methods (applications)

  • Method introduction

    Method Name Explain
    T get() Return value if value exists, otherwise throw NoSuchElementException
    boolean isPresent() Returns true if a value exists, false otherwise
  • Sample Code

    public class OptionalDemo2 {
        public static void main(String[] args) {
            //get() Returns a value if it exists, otherwise throws NoSuchElementException
            //public boolean isPresent() determines if the object encapsulated by Optional is not empty, returns true if it is not empty, or false if it is not
    
            //Student s = new Student("zhangsan",23);
            Student s = null;
            Optional<Student> optional = Optional.ofNullable(s);
            //If the encapsulation is a null, retrieving it through the get method throws a NoSuchElementException.
            if(optional.isPresent()){
                Student student = optional.get();
                System.out.println(student);
            }else{
                System.out.println("Optional Encapsulated object is empty");
            }
        }
    }
    

4.3 Methods for handling null pointers (applications)

  • Method introduction

    Method Name Explain
    T orElse(T other) If not null, return the specific value, otherwise return the value in the parameter
    T orElseGet(Supplier<? extends T> supplier) If not null, return the specific value, otherwise return the result from the function in parentheses
    void ifPresent (Consumer<? super T> action) If not null, use this value to perform the given action, otherwise no action is performed
    void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) If not null, the value is used to perform the given operation, otherwise the given null-based operation is performed
  • Sample Code

    public class OptionalDemo3 {
        public static void main(String[] args) {
            //method1();
    
            //method2();
            //method3();
            //method4();
    
        }
    
        private static void method4() {
            //Student s = new Student("zhangsan",23);
            Student s = null;
            Optional<Student> optional = Optional.ofNullable(s);
            //public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction),
            //If not null, the value is used to perform the given operation, otherwise the given null-based operation is performed.
            optional.ifPresentOrElse(student -> System.out.println(student),
                    ()->System.out.println("Empty"));
        }
    
        private static void method3() {
            //Student s = new Student("zhangsan",23);
            Student s = null;
            Optional<Student> optional = Optional.ofNullable(s);
            //ifPresent (Consumer<? super T> action)
            //If not null, use this value to perform the given action, otherwise no action is performed
            optional.ifPresent(student -> System.out.println(student));
        }
    
        private static void method2() {
            Student s = new Student("zhangsan",23);
            //Student s = null;
            Optional<Student> optional = Optional.ofNullable(s);
            //orElseGet(Supplier<? extends T> supplier)
            //If not null, return the specific value, otherwise return the result from the function in parentheses
    
            Student student = optional.orElseGet(()-> new Student("lisi" , 24));
            System.out.println(student);
        }
    
        private static void method1() {
            //Student s = new Student("zhangsan",23);
            Student s = null;
            Optional<Student> optional = Optional.ofNullable(s);
            //orElse(T other) returns a specific value if it is not empty, otherwise returns the value in the parameter
            Student student = optional.orElse(new Student("lisi", 24));
            System.out.println(student);
        }
    }
    

Keywords: Java

Added by MrPen on Mon, 22 Nov 2021 01:25:21 +0200