Java common class II

array

Arrays is a tool class that operates on arrays.

Common member methods

public static String toString(int[] a) //Convert array to string
public static void sort(int[] a) //Sort the array
public static int binarySearch(int[] a,int key) //Binary search

The toString() source code is as follows:

public static String toString(int[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(a[i]);
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

binarySearch() calls binarySearch0(), and the source code of binarySearch0() is as follows:

private static int binarySearch0(int[] a, int fromIndex, int toIndex,int key) {
    int low = fromIndex;
    int high = toIndex - 1;

    while (low <= high) {
        int mid = (low + high) >>> 1;
        int midVal = a[mid];

        if (midVal < key)
            low = mid + 1;
        else if (midVal > key)
            high = mid - 1;
        else
            return mid; // key found
    }
    return -(low + 1);  // key not found.
}

Use example

public class ArraysDemo {
    public static void main(String[] args) {
        // Define an array
        int[] arr = { 24, 69, 80, 57, 13 };

        // public static String toString(int[] a) convert array to string
        System.out.println("Before sorting:" + Arrays.toString(arr));//Before sorting: [24, 69, 80, 57, 13]

        // public static void sort(int[] a) sorts the array
        Arrays.sort(arr);
        System.out.println("After sorting:" + Arrays.toString(arr));//After sorting: [13, 24, 57, 69, 80]

        // [13, 24, 57, 69, 80]
        // public static int binarySearch(int[] a,int key) binary search
        System.out.println("binarySearch:" + Arrays.binarySearch(arr, 57));//binarySearch:2
        System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577));//binarySearch:-6
    }
}

Big Mike

BigDecimal class: immutable and arbitrary precision signed decimal, which can solve the problem of data loss.

Look at the following procedure and write the results:

public static void main(String[] args) {
    System.out.println(0.09 + 0.01); // 0.09999999999999999
    System.out.println(1.0 - 0.32);  // 0.6799999999999999
    System.out.println(1.015 * 100); // 101.49999999999999
    System.out.println(1.301 / 100); // 0.013009999999999999
    System.out.println(1.0 - 0.12); // 0.88
}

The result is a little different from what we thought, because the data storage of floating-point number type is different from that of integer. Most of the time, they have significant digits. Because the float type and double are easy to lose precision during operation, in order to accurately represent and calculate floating-point numbers, Java provides BigDecimal.

Common member methods

public BigDecimal(String val) //Construction method

public BigDecimal add(BigDecimal augend) //plus

public BigDecimal subtract(BigDecimal subtrahend)//reduce

public BigDecimal multiply(BigDecimal multiplicand) //ride

public BigDecimal divide(BigDecimal divisor) //except

public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)
//Division, scale: how many decimal places, roundingMode: how to round off

Use example

public static void main(String[] args) {
    /*System.out.println(0.09 + 0.01);
    System.out.println(1.0 - 0.32);
    System.out.println(1.015 * 100);
    System.out.println(1.301 / 100);
    System.out.println(1.0 - 0.12);*/

    BigDecimal bd1 = new BigDecimal("0.09");
    BigDecimal bd2 = new BigDecimal("0.01");
    System.out.println("add:" + bd1.add(bd2));//add:0.10
    System.out.println("-------------------");

    BigDecimal bd3 = new BigDecimal("1.0");
    BigDecimal bd4 = new BigDecimal("0.32");
    System.out.println("subtract:" + bd3.subtract(bd4));//subtract:0.68
    System.out.println("-------------------");

    BigDecimal bd5 = new BigDecimal("1.015");
    BigDecimal bd6 = new BigDecimal("100");
    System.out.println("multiply:" + bd5.multiply(bd6));//multiply:101.500
    System.out.println("-------------------");

    BigDecimal bd7 = new BigDecimal("1.301");
    BigDecimal bd8 = new BigDecimal("100");
    System.out.println("divide:" + bd7.divide(bd8));//divide:0.01301

    //rounding
    System.out.println("divide:"
            + bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP));//Keep three significant digits  
    //divide:0.013

    System.out.println("divide:"
            + bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP));//Retain eight significant digits
    //divide:0.01301000
}

Biggitger

BigInteger: data beyond the range of Integer can be used for operation.

Common member methods

public BigInteger add(BigInteger val) //plus

public BigInteger subtract(BigInteger val) //reduce

public BigInteger multiply(BigInteger val) //ride

public BigInteger divide(BigInteger val) //except

public BigInteger[] divideAndRemainder(BigInteger val)//Returns an array of quotients and residuals

Use example

Example 1:

public class BigIntegerDemo {
    public static void main(String[] args) {
        Integer num = new Integer("2147483647");
        System.out.println(num);

        //Integer num2 = new Integer("2147483648");
        // Exception in thread "main" java.lang.NumberFormatException: For input string: "2147483648"
        //System.out.println(num2);

        // Creating objects with BigIntege r
        BigInteger num2 = new BigInteger("2147483648");
        System.out.println(num2);
    }
}

Example 2:

public class BigIntegerDemo2 {
    public static void main(String[] args) {
        BigInteger bi1 = new BigInteger("100");
        BigInteger bi2 = new BigInteger("50");

        // public BigInteger add(BigInteger val): add
        System.out.println("add:" + bi1.add(bi2)); //add:150
        // public BigInteger subtract(BigInteger Val): minus
        System.out.println("subtract:" + bi1.subtract(bi2));//subtract:50
        // public BigInteger multiply(BigInteger val): multiply
        System.out.println("multiply:" + bi1.multiply(bi2));//multiply:5000
        // public BigInteger divide(BigInteger val): divide
        System.out.println("divide:" + bi1.divide(bi2));//divide:2

        // Public BigInteger [] divideandremander (BigInteger VAL): returns an array of quotient and remainder
        BigInteger[] bis = bi1.divideAndRemainder(bi2);
        System.out.println("divide: " + bis[0]);//divide: 2
        System.out.println("remainder: " + bis[1]);//remainder: 0
    }
}

character

The Character class wraps the value of a basic type Character in an object In addition, this class provides several methods to determine the category of characters (lowercase letters, numbers, etc.) and convert characters from uppercase to lowercase and vice versa.

Common member methods

Character(char value) //Construction method

public static boolean isUpperCase(char ch) //Determines whether a given character is uppercase

public static boolean isLowerCase(char ch) //Determines whether a given character is lowercase

public static boolean isDigit(char ch) //Judge whether the given character is a numeric character

public static char toUpperCase(char ch) //Converts a given character to uppercase

public static char toLowerCase(char ch) //Converts a given character to lowercase

Use example

public class CharacterDemo {
    public static void main(String[] args) {
        // public static boolean isUpperCase(char ch): judge whether a given character is uppercase
        System.out.println("isUpperCase:" + Character.isUpperCase('A'));//true
        System.out.println("isUpperCase:" + Character.isUpperCase('a'));//false
        System.out.println("isUpperCase:" + Character.isUpperCase('0'));//false
        System.out.println("-----------------------------------------");

        // public static boolean isLowerCase(char ch): judge whether a given character is lowercase
        System.out.println("isLowerCase:" + Character.isLowerCase('A'));//false
        System.out.println("isLowerCase:" + Character.isLowerCase('a'));//true
        System.out.println("isLowerCase:" + Character.isLowerCase('0'));//false
        System.out.println("-----------------------------------------");

        // public static boolean isDigit(char ch): judge whether a given character is a numeric character
        System.out.println("isDigit:" + Character.isDigit('A'));//false
        System.out.println("isDigit:" + Character.isDigit('a'));//false
        System.out.println("isDigit:" + Character.isDigit('0'));//true
        System.out.println("-----------------------------------------");

        // public static char toUpperCase(char ch): converts a given character to uppercase
        System.out.println("toUpperCase:" + Character.toUpperCase('A'));//A
        System.out.println("toUpperCase:" + Character.toUpperCase('a'));//A
        System.out.println("-----------------------------------------");

        // Public static char to lowercase (char CH): converts a given character to lowercase
        System.out.println("toLowerCase:" + Character.toLowerCase('A'));//a
        System.out.println("toLowerCase:" + Character.toLowerCase('a'));//a
    }
}

practice

Count the occurrence times of uppercase, lowercase and numeric characters in a string. (other characters are not considered)

/**
 *  Count the occurrence times of uppercase, lowercase and numeric characters in a string. (other characters are not considered)
 *
 * analysis:
 *         A:Define three statistical variables.
 *             int bigCont=0;
 *             int smalCount=0;
 *             int numberCount=0;
 *         B:Enter a string on the keyboard.
 *         C:Converts a string to an array of characters.
 *         D:Traverse the character array to get each character
 *         E:Judge whether the character is
 *             Capital bigCount + +;
 *             Lowercase smalCount + +;
 *             numberCount + +;
 *         F:Just output the result
 */
public class CharacterTest {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String str=sc.nextLine();
        printCount(str);
        printCount2(str);
    }

    //Original writing
    public static void printCount(String str) {
        int numberCount=0;
        int lowercaseCount=0;
        int upercaseCount=0;

        for(int index=0;index<str.length();index++){
            char ch=str.charAt(index);
            if(ch>='0' && ch<='9'){
                numberCount++;
            }else if(ch>='A' && ch<='Z'){
                upercaseCount++;
            }else if(ch>='a' && ch<='z'){
                lowercaseCount++;
            }
        }
        System.out.println("Number yes"+numberCount+"individual");
        System.out.println("There are lowercase letters"+lowercaseCount+"individual");
        System.out.println("There are capital letters"+upercaseCount+"individual");
    }

    //Use wrapper classes to improve
    public static void printCount2(String str) {
        int numberCount=0;
        int lowercaseCount=0;
        int upercaseCount=0;

        for(int index=0;index<str.length();index++){
            char ch=str.charAt(index);
            if(Character.isDigit(ch)){
                numberCount++;
            }else if(Character.isUpperCase(ch)){
                upercaseCount++;
            }else if(Character.isLowerCase(ch)){
                lowercaseCount++;
            }
        }
        System.out.println("Number yes"+numberCount+"individual");
        System.out.println("Lowercase letters have"+lowercaseCount+"individual");
        System.out.println("Capital letters have"+upercaseCount+"individual");
    }
}

Scanner

Scanner: used to receive keyboard input data. Use scanner Trilogy: guide package, create object and use corresponding methods.

Common member methods

Scanner(InputStream source) //Construction method

public boolean hasNextXxx() 
//Judge whether it is an element of a certain type. Xxx represents the type, such as public boolean hasNextInt()

public Xxx nextXxx() //Get the element. Xxx represents the type, such as public int nextInt()

Use example

Example 1:

public class ScannerDemo {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        if(sc.hasNextInt()){
            int x=sc.nextInt();
            System.out.println("x="+x);
        }else{
            System.out.println("The input data is incorrect");
        }
    }
}

Example 2: get a value first, wrap a line, and then get a string. There will be a problem. Main reason: it is the problem of line feed symbol. How to solve it?

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

    //Enter 12 to wrap and output "sss"
    int x=sc.nextInt();
    System.out.println("x:"+x); //x:12

    String line=sc.nextLine(); //There will be a problem because the newline character will be input as a character
    System.out.println("line:"+line); //line:
}

Solution 1: first obtain a value, and then create a new keyboard entry object to obtain the string.

public static void method() {
    Scanner sc=new Scanner(System.in);
    int x=sc.nextInt();
    System.out.println("x:"+x);

    Scanner sc2=new Scanner(System.in);
    String line=sc2.nextLine();
    System.out.println("line:"+line);
}

Solution 2: get all the data according to the string first, and then convert what you want.

public static void method2() {
    Scanner sc=new Scanner(System.in);

    String xStr=sc.nextLine();
    String line=sc.nextLine();

    int x=Integer.parseInt(xStr);

    System.out.println("x:"+x);
    System.out.println("line:"+line);
}

calendar

Calendar is associated with a group such as YEAR, MONTH and day for a specific moment_ OF_ The conversion between calendar fields such as MONTH and HOUR provides some methods, and provides some methods for operating calendar fields (such as obtaining the date of the next week).

Common member methods

public int get(int field) 
//Returns the value of the given calendar field. Each calendar field in the calendar class is a static member variable and is of type int.

public void add(int field,int amount)
//Operate the current calendar according to the given calendar field and the corresponding time.

public final void set(int year,int month,int date)
//Set the month, year and day of the current calendar

Use example

Example 1:

public class CalendarDemo {
    public static void main(String[] args) {
        // Its calendar fields have been initialized by the current date and time:
        Calendar rightNow = Calendar.getInstance(); // Subclass object
        int year=rightNow.get(Calendar.YEAR);
        int month=rightNow.get(Calendar.MONTH);//Note that the month starts at 0
        int date=rightNow.get(Calendar.DATE);
        System.out.println(year + "year" + (month + 1) + "month" + date + "day");
        //December 25, 2018
    }
}

Example 2:

public class CalendarDemo2 {
    public static void main(String[] args) {
        // Its calendar fields have been initialized by the current date and time:
        Calendar calendar = Calendar.getInstance(); // Subclass object
        System.out.println(getYearMonthDay(calendar));//December 25, 2018

        //Three years ago today
        calendar.add(Calendar.YEAR,-3);
        System.out.println(getYearMonthDay(calendar));//December 25, 2015

        //Five years later, 10 days ago
        calendar.add(Calendar.YEAR,5);
        calendar.add(Calendar.DATE,-10);
        System.out.println(getYearMonthDay(calendar));//December 15, 2020

        //Set November 11, 2011
        calendar.set(2011,10,11);
        System.out.println(getYearMonthDay(calendar));//November 11, 2011
    }

    //Get year, month and day
    public static String getYearMonthDay(Calendar calendar){
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH);
        int date=calendar.get(Calendar.DATE);
        return year + "year" + (month + 1) + "month" + date + "day";
    }
}

practice

Get the number of days in February of any year

/**
 *Get the number of days in February of any year
 *analysis:
 *         A:Enter any year on the keyboard
 *         B:Set the month, year and day of the calendar object
 *             Year is the input data
 *             The month is February
 *             Day is 1
 *         C:Push the time forward one day, which is the last day of February
 *         D:Just get the output of this day
 */
public class CalendarTest {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int year=sc.nextInt();
        Calendar c= Calendar.getInstance();
        c.set(year,2,1); //What you get is March 1 of that year
        c.add(Calendar.DATE,-1);//Push the time forward one day, which is the last day of February
        //public void add(int field,int amount): operate the current calendar according to the given calendar field and the corresponding time.

        System.out.println(year+"In February"+c.get(Calendar.DATE)+"day");
    }
}

date

Date: represents a specific moment, accurate to milliseconds.

Common member methods

Date() //Creates a date object based on the current default millisecond value

Date(long date) //Creates a date object based on the given millisecond value

public long getTime() //Gets the time in milliseconds

public void setTime(long time) //Set time

Use example

/**
 * There are two ways to convert a millisecond value to Date:
 * (1)Construction method
 * (2)setTime(long time)
 */
public class DateDemo {
    public static void main(String[] args) {
        // Date(): creates a date object based on the current default millisecond value
        Date d = new Date();
        System.out.println("d:" + d);
        //d: Tue Dec 25 20:01:17 GMT + 08:00 2018 -- > current time

        // Date(long date): creates a date object based on the given millisecond value
        //long time = System.currentTimeMillis();
        long time = 1000 * 60 * 60; // 1 hour
        Date d2 = new Date(time);
        System.out.println("d2:" + d2);
        //00:00 GMT, January 1, 1970
        //Thu Jan 01 09:00:00 GMT + 08:00 1970 GMT + means standard time plus 8 hours, because China is the eighth east zone

        // Get time
        long time2 = d.getTime();
        System.out.println(time2); //1545739438466 MS
        System.out.println(System.currentTimeMillis());

        // Set time
        d.setTime(1000*60*60);
        System.out.println("d:" + d);
        //Thu Jan 01 09:00:00 GMT+08:00 1970
    }
}

Mutual conversion of Date and String types

public class DateFormatDemo {
    public static void main(String[] args) {
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy year MM month dd day");
        String s=dateToString(date,sdf);
        System.out.println(s); //December 25, 2018
        System.out.println(stringToDate(s,sdf));//Tue Dec 25 00:00:00 GMT+08:00 2018
    }

    /**
     * Date     --     String(Format)
     *         public final String format(Date date)
     */
    public static String dateToString(Date d, SimpleDateFormat sdf) {
        return sdf.format(d);
    }

    /**
     * * String -- Date((parsing)
     *         public Date parse(String source)
     */
    public static Date stringToDate(String s, SimpleDateFormat sdf){
        Date date=null;
        try {
            date=sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}

 

Date format

DateForamt: you can format and parse dates and strings, but because it is an abstract class, you can use the concrete subclass SimpleDateFormat.

SimpleDateForrmat construction method

SimpleDateFormat() //Default mode

SimpleDateFormat(String pattern) //Given mode

How to write this pattern string? By looking at the API, we can find the corresponding pattern:

Chinese descriptionPattern character
yeary
monthM
dayd
TimeH
branchm
seconds

practice

How many days have you been in this world?

Small exercise:/**
 * *
 * How many days have you been in this world?
 *
 * analysis:
 *         A:Enter your date of birth on the keyboard
 *         B:Convert the string to a date
 *         C:Get a millisecond value from this date
 *         D:Gets the millisecond value of the current time
 *         E:Get a millisecond value with D-C
 *         F:Convert the millisecond value of E to year
 *             /1000/60/60/24
 */
public class DateTest {
    public static void main(String[] args) throws ParseException {
        // Enter your date of birth on the keyboard
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter your date of birth(format yyyy-MM-dd):");
        String line = sc.nextLine();

        // Convert the string to a date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sdf.parse(line);
        long birth=d.getTime(); //Time of birth
        long current=System.currentTimeMillis();//current time 

        long days=(current-birth)/1000/60/60/24;
        System.out.println("You were born"+days+"day");
    }
}

Keywords: Java Algorithm leetcode

Added by Cultureshock on Sat, 19 Feb 2022 01:06:59 +0200