Random
use
package day_7_14_Random; import java.util.Random; /** * random number * * @author Ah Chao * @Date 2021 July 14 */ public class Random_1 { public static void main(String[] args){ //Create random number generator Random random=new Random(); //Randomly generate once from 0 -- 4 int i=random.nextInt(5); System.out.println(i); //Generate 10 -- 20 //Nextint (max min + 1) + min int x=random.nextInt(11)+10; System.out.println(x); // 5--9 System.out.println(random.nextInt(9-5+1)+5); //Generate a-z int c=random.nextInt(26); char c1=(char)(c+97); System.out.println(c1); } }
Number
Decimal format / / decimal format
package day_14_number; import java.text.DecimalFormat; /** * * * * * java.text.DecimalFormat; * #Any number 0-9 single number * ,Thousandth * .decimal point * 0 Complement * * * @author Ah Chao * @Date 2021 July 14 */ public class Number_01 { public static void main(String[] args) { //Create a number formatting object //Join the thousandth percentile DecimalFormat df=new DecimalFormat(",#,####,###"); System.out.println(df.format(123456789));//123,456,789 //Add the thousandth place and keep two decimal places df=new DecimalFormat(",######.##"); //Will be rounded System.out.println(df.format(1234567.887)); //1,234567.89 //Add the thousandth place, keep two decimal places, and make up 0 if it is not enough df=new DecimalFormat(",###.0000"); System.out.println(df.format(123456.155)); //123,456.1550 } }
BigInteger & BigDecimal / / large integer & large decimal
summary
java.lang.Math provides a series of static methods for scientific calculation. The parameters and returns of its methods
The value type is usually double.
abs absolute value acos,asin,atan,cos,sin,tan trigonometric function sqrt square root
log natural logarithm of pow (double a, double b) a to the power of b
exp e is the bottom index
max(double a,double b)
min(double a,double b)
random() returns a random number from 0.0 to 1.0
Long round (double a) data a of double type is converted to long type (rounded)
Todegrees (double angle) radians - > angle
toRadians(double angdeg) angle - > radians
8. BigInteger and BigDecimal classes
8.1 BigInteger
1. As the wrapper class of int, the Integer class can store a maximum Integer value of 231-1, and the Long class is also limited, with a maximum of 263-1. If you want to represent a large Integer, neither the basic data type nor their wrapper class can do anything, let alone operate.
2,java. The BigInteger of the math package can represent an immutable integer of arbitrary precision. BigInteger provides
The equivalent of all Java's basic integer operators, and provides Java All relevant methods of lang. math. In addition, BigInteger also provides the following operations: modular arithmetic, GCD calculation, prime test, prime generation, bit operation, and some other operations.
3. Constructor
BigInteger(String val): build BigInteger objects based on strings
4. Common methods
public BigInteger abs(): BigInteger that returns the absolute value of this BigInteger.
BigInteger add(BigInteger val): returns the BigInteger whose value is (this + val)
BigInteger subtract(BigInteger val): returns the BigInteger whose value is (this - val)
BigInteger multiply(BigInteger val): returns a BigInteger with a value of (this * val)
BigInteger divide(BigInteger val): returns a BigInteger with a value of (this / val). Integer division preserves only the integer part.
BigInteger remaining (BigInteger VAL): returns a BigInteger with a value of (this% VAL).
BigInteger [] divideandremander (BigInteger VAL): returns an array containing two BigIntegers (this / val) followed by (this% VAL).
BigInteger pow(int exponent): returns a BigInteger whose value is (thisexponent).
8.2 BigDecimal
l general Float and Double classes can be used for scientific calculation or engineering calculation, but in commercial calculation, high digital accuracy is required, so Java math. BigDecimal class.
The lBigDecimal class supports immutable signed decimal points of arbitrary precision.
l constructor
public BigDecimal(double val)
public BigDecimal(String val)
l common methods
public BigDecimal add(BigDecimal augend)
public BigDecimal subtract(BigDecimal subtrahend)
public BigDecimal multiply(BigDecimal multiplicand)
public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
use
package day_14_number; import java.math.BigInteger; import java.math.BigDecimal; /** * * java.math.BigInteger And BigDecimal are extremely accurate * * @author Ah Chao * @Date 2021 July 14 */ public class bigDecimal_1 { public static void main(String[] args){ //When creating this object, you need to pass the number of string BigInteger bi=new BigInteger("33"); BigDecimal v1=new BigDecimal("20"); BigDecimal v2=new BigDecimal("20"); //+Cannot v1+v2 because this is an application type BigDecimal v3=v1.add(v2); //- v3=v1.subtract(v2); //* v3=v1.multiply(v2); // / v3=v1.remainder(v2); System.out.println(v3); } }
Factorial
package day_14_number; import java.math.BigDecimal; public class BigDecimal_02 { public static void main(String[] args){ long result=m1(33); System.out.println(result); BigDecimal result1=m2(100); System.out.println(result1); } public static long m1(int n){ if(n<=1){ return 1; }return n*m1(n-1); } public static BigDecimal m2(int n){ if(n<=1){ return new BigDecimal(1); }return new BigDecimal(n).multiply(m2(n-1)); } }
Math
summary
math provides scientific calculation and basic digital operation methods
* all are static methods, which can be called by class name, and Match is in Java Lang, you do not need to import packages
common method
package _Match; /** * * math It provides scientific calculation and basic digital operation methods * All are static methods, which can be called by class name, and Match is in Java Lang, you do not need to import packages * * @author Ah Chao * @Date 2021 July 14 */ public class math_1 { public static void main(String[] args){ //abs absolute value System.out.println(Math.abs(-25)); //25 //ceil rounded up, decimal greater than 0 into 1 System.out.println(Math.ceil(1.001)); //2 //floor rounding down and discarding decimals System.out.println(Math.floor(1.9)); //1.0 //Square root of sqrt System.out.println(Math.sqrt(4)); //2.0 //cbrt cube root System.out.println(Math.cbrt(8)); //2.0 //rint rounding //Banker's algorithm, rounding consideration, even number System.out.println(Math.rint(2.5)); //2.0 System.out.println(Math.rint(3.5)); // 4.0 // pow N power System.out.println(Math.pow(2,3)); //8.0 } }
Abnormal mechanism
Anomalies seen before
1 subscript out of bounds (array)
2 null pointer exception (array, object-oriented)
3 stack memory removal (recursion)
4 type conversion exception (object-oriented)
5 number formatting exception (common API)
summary
Exception:
* is a response mechanism provided by java to identify errors, which can make the program more robust and easy to debug
* exception is another way of saying that is wrong
* there is a class in java that specifically simulates all exceptions. Throwable is the ancestor of the exception class, and all exception classes are its subclasses
* if an exception occurs in the program, the program life cycle execution will be terminated, so it needs to be handled,
*
*
* exception handling form
* try...catch.... : to solve the exception, which is generally used at the client (at the call)
* throws: throws exceptions, which are generally used at the class library side (the server side, where they are called)
* throw: abnormal source, creating exception and creating exception object
Inheritance system
Error
concept
x system internal errors, which are handled by the system, and the program itself does not need to capture and handle.
For example: oom (memory overflow), virtualmachineerror (virtual machine error), stackoverflowerror (stack overflow error, etc.), in general, the JVM will choose to terminate the program.
Exception
summary
Exception is the parent of all exception classes. It is divided into non RuntimeException and RuntimeException.
n non RuntimeException
It refers to the exceptions that need to be caught or handled during program compilation, such as IOException, custom exception, etc. This is a checked exception.
nRuntimeException
It refers to exceptions that do not need to be caught or handled during program compilation, such as NullPointerException, etc. Is an unchecked exception. It is usually caused by the carelessness of programmers. Such as null pointer exception, array out of bounds, type conversion exception, etc.
common method
try...cath...
First kind
package com; /** * Exception: * It is a response mechanism provided by java to identify errors, which can make the program more robust and easy to debug * Exception is another way of saying that is wrong * java There is a class in which all exceptions are simulated. Throwable is the ancestor of the exception class, and all exception classes are its subclasses * If an exception occurs in the program, the program life cycle execution will be terminated, so it needs to be handled, * * * Exception handling form * try...catch.... : Exception resolution is generally used on the client (at the call) * throws : Throwing exceptions is generally used on the class library side (the server side, where it is called) * throw : Abnormal source, making exception and creating exception object * * */ public class Exception_01 { public static void main(String[] args) { int a = 2; int b = 0; // Using if can solve most of the errors, but if can only solve the predictable ones, and the unpredictable ones cannot be solved if (b == 0) { System.out.println("Divisor cannot be 0"); return; } System.out.println(a/b); } }
package com; import java.io.FileInputStream; import java.io.FileNotFoundException; /** * Syntax: * try{ * High risk code; * }catch (Exception type (variable){ * Operation after error; * } * * */ public class Exception_02 { public static void main(String[] args) { try { // High risk code, error prone code // This file may not be found, so we need to deal with it FileInputStream fis = new FileInputStream("D://Aa.txt"); // The code after the Error statement in try is not executed, and catch is executed System.out.println("xxx"); } catch (FileNotFoundException e) { // Print tracking stack frame, which is convenient for programmers to debug // e.printStackTrace(); // Get error information and respond to user's convenience String msg = e.getMessage(); System.out.println(msg); // Handling measures after error // System.out.println("file does not exist"); } // The code can execute normally System.out.println("==============="); } }
Second
try{
High risk code
}Catch (exception type variable){
}Catch (exception type variable){
}
public static void main(String[] args) { try { new FileInputStream("D:/a.t2xt"); String s = null; s.equals(""); // You can write multiple catches to catch multiple exceptions for different processing // Multiple exception types cannot have inheritance relationship, otherwise they must be from subclass to parent class, otherwise the exception object will be obtained due to polymorphism } catch (FileNotFoundException e) { System.out.println("cannot find file"); } catch (NullPointerException e) { System.out.println("Null pointer"); } }
Third
java1.7 new improvements
*
* automatically close resources
*
* try (open resource) {
* high risk code;
*}catch (exception type variable){
*
* }
package com; import java.io.FileInputStream; import java.io.IOException; /** * java1.7 New improvement * * Automatically close resources * * try( Open resource;) { * High risk code; * }catch(Exception type (variable){ * * } * * */ public class Exception_07 { public static void main(String[] args) { FileInputStream fis1 = null; try( FileInputStream fis = new FileInputStream("D://a.txt"); // Resource 2 // Resource 3 ){ // Operation, automatic shutdown, not finally fis1=fis; System.out.println(fis.read()); }catch (Exception e) { e.printStackTrace(); } try { // Stream Closed System.out.println(fis1.read()); } catch (IOException e) { e.printStackTrace(); } } }
Throws
Throws throws an exception, which is a reminder. Tell the caller that there may be an exception here
*
* multiple exceptions can be thrown, separated by commas
package com; import java.io.FileInputStream; import java.io.FileNotFoundException; /** * throws Throwing an exception is a reminder. Explain to the caller that there may be an exception here * * Multiple exceptions can be thrown, separated by commas * * */ public class Exception_04 { public static void main(String[] args) { try { m1(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } System.out.println("========="); } public static void m1() throws FileNotFoundException, Exception, NullPointerException { m2(); } public static void m2() throws FileNotFoundException { new FileInputStream(""); } }
Finally
package com; /** * finally : It is a statement that must be executed. There is only one case that it is not executed, system exit(0); * * 1 finally Cannot be used alone. 2 must be used with try or try Use with catch * * @author Dawn Education - handsome and juicy, brother Ze * @Date 2021 July 14, 2014 2:18:39 PM */ public class Exception_05 { public static void main(String[] args) { try { String s = null; s.equals(""); // Null pointer exception, terminating program life cycle } finally { // Must execute System.out.println("====="); } // Because of catch, there is no way to catch exceptions, and the life cycle will still be terminated, so the following code will not be executed System.out.println("-----------="); } }
There can be no broader exceptions
class A { public void m1() throws FileNotFoundException { } } class B extends A { // The exception class thrown is either the same as the exception class thrown by the parent class // Or it is the subclass of the exception class thrown by the parent class // Or don't throw an exception public void m1() throws FileNotFoundException { }
Custom exception
grammar
Custom exception class:
* 1 inherit an existing exception class
* generally, we can inherit Exception
* if it is a runtime exception, continue with RuntimeException
* 2 public parameterless structure
* 3. The parameter structure is passed in String, which is an error message
package ThrowExample.test; /** * Custom exception class: * 1 Inherit an existing exception class * Generally, we can inherit Exception * If it is a runtime exception, continue with RuntimeException * 2 Public nonparametric construction * 3 The parameter structure is passed in String, which is an error message * * */ public class Test extends Exception { public Test() { } public Test(String msg) { super(msg); } }
Application scenario
* demand:
* complete user login
* 1 user has three attributes: username, password and nickname
* 2 business logic class, which provides login methods to verify whether the login is successful
* prepare user array and save user information (equivalent to database)
* 3 the input parameter is the user name and password, and the output parameter is also the user object. After successful login, all information of the user will be returned
* 4 client class, which receives user input and performs login verification
User class
database
dao
service
controller