A digital class
1.1 Large number of floating-point numbers
BigDecimal b1 = new BigDecimal("123456789.987654321"); // 声明BigDecimal对象
BigDecimal b2 = new BigDecimal("987654321.123456789"); // 声明BigDecimal对象
System.out.println("b1: " + b1 + ", b2:" + b2);
System.out.println("加法操作:" + b2.add(b1)); // 加法操作
System.out.println("减法操作:" + b2.subtract(b1)); // 减法操作
System.out.println("乘法操作:" + b2.multiply(b1)); // 乘法操作
//需要指定位数,防止无限循环,或者包含在try-catch中
System.out.println("除法操作:" + b2.divide(b1,10,BigDecimal.ROUND_HALF_UP)); // 除法操作包留十位小数进行四舍五入
System.out.println("最大数:" + b2.max(b1)); // 求出最大数
System.out.println("最小数:" + b2.min(b1)); // 求出最小数
int flag = b1.compareTo(b2);
if (flag == -1)
System.out.println("比较操作: b1<b2");
else if (flag == 0)
System.out.println("比较操作: b1==b2");
else
System.out.println("比较操作: b1>b2");
System.out.println("===================");
//尽量采用字符串赋值
System.out.println(new BigDecimal("2.3"));
1.2 large integer
BigInteger b1 = new BigInteger("123456789"); // 声明BigInteger对象
BigInteger b2 = new BigInteger("987654321"); // 声明BigInteger对象
System.out.println("b1: " + b1 + ", b2:" + b2);
System.out.println("加法操作:" + b2.add(b1)); // 加法操作
System.out.println("减法操作:" + b2.subtract(b1)); // 减法操作
System.out.println("乘法操作:" + b2.multiply(b1)); // 乘法操作
System.out.println("除法操作:" + b2.divide(b1)); // 除法操作
System.out.println("最大数:" + b2.max(b1)); // 求出最大数
System.out.println("最小数:" + b2.min(b1)); // 求出最小数
BigInteger result[] = b2.divideAndRemainder(b1); // 求出余数的除法操作
System.out.println("商是:" + result[0] + ";余数是:" + result[1]);
System.out.println("等价性是:" + b1.equals(b2));
int flag = b1.compareTo(b2);
if (flag == -1)
System.out.println("比较操作: b1<b2");
else if (flag == 0)
System.out.println("比较操作: b1==b2");
else
System.out.println("比较操作: b1>b2");
1.3 Random Number:
import java.util.Random;
public class RandomTest {
public static void main(String[] args)
{
//第一种办法,采用Random类 随机生成在int范围内的随机数
Random rd = new Random();
System.out.println(rd.nextInt());
System.out.println(rd.nextInt(100)); //0--100的随机数
System.out.println(rd.nextLong());
System.out.println(rd.nextDouble()); //返回0.0~1.0直接的数
System.out.println("=========================");
//第二种,生成一个范围内的随机数 例如0到时10之间的随机数
//Math.random[0,1)
System.out.println(Math.round(Math.random()*10));
System.out.println("=========================");
//JDK 8 新增方法
rd.ints(); //返回无限个int类型范围内的数据
int[] arr = rd.ints(10).toArray(); //生成10个int范围类的个数。
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println("=========================");
arr = rd.ints(5, 10, 100).toArray();//限制范围10~100
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println("=========================");
arr = rd.ints(10).limit(5).toArray();//表示生成10个限定返回5个
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
1.4 formatted output
public class MathTest {
public static void main(String[] args) {
System.out.println(Math.abs(-5)); //绝对值
System.out.println(Math.max(-5,-8)); //最大值
System.out.println(Math.pow(-5,2)); //求幂
System.out.println(Math.round(3.5)); //四舍五入
System.out.println(Math.ceil(3.5)); //向上取整
System.out.println(Math.floor(3.5)); //向下取整
}
}
输出:
5
-5
25.0
4
4.0
3.0
And double precision floating point 1.5
float f1 = 1.23f;
// float f2 = 1.23; error, float赋值必须带f
double d1 = 4.56d;
double d2 = 4.56; //double 可以省略末尾d
Second, the string
2.1String
public class StringTest {
public static void main(String[] args) {
String a = "123;456;789;123 ";
System.out.println(a.charAt(0)); // 返回第0个元素
System.out.println(a.indexOf(";")); // 返回第一个;的位置
System.out.println(a.concat(";000")); // 连接一个新字符串并返回,a不变
System.out.println(a.contains("000")); // 判断a是否包含000
System.out.println(a.endsWith("000")); // 判断a是否以000结尾
System.out.println(a.equals("000")); // 判断是否等于000
System.out.println(a.equalsIgnoreCase("000"));// 判断在忽略大小写情况下是否等于000
System.out.println(a.length()); // 返回a长度
System.out.println(a.trim()); // 返回a去除前后空格后的字符串,a不变
String[] b = a.split(";"); // 将a字符串按照;分割成数组
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
System.out.println("===================");
System.out.println(a.substring(2, 5)); // 截取a的下标为2(第三个)到下标为5(第6个)字符 a不变
System.out.println(a.replace("1", "a"));
System.out.println(a.replaceAll("1", "a")); // replaceAll第一个参数是正则表达式
System.out.println("===================");
String s1 = "12345?6789";
String s2 = s1.replace("?", "a");
String s3 = s1.replaceAll("[?,8]", "a");
// 这里的[?] 才表示字符问号,这样才能正常替换。不然在正则中会有特殊的意义就会报异常
System.out.println(s2);
System.out.println(s3);
System.out.println(s1.replaceAll("[\\d]", "a")); //将s1内所有数字替换为a并输出,s1的值未改变。
}
}
输出:
1
3
123;456;789;123 ;000
false
false
false
false
16
123;456;789;123
123
456
789
123
===================
3;4
a23;456;789;a23
a23;456;789;a23
===================
12345a6789
12345a67a9
aaaaa?aaaa
Brief Description of the 2.2 regular expression:
?, *, +, \ d , \ w are equivalent character
? match length equivalent to {0,1}
* {0 equivalent to the match length}
+ equivalent length of the matched. 1 {,}
\ D, etc. is equivalent to [0-9]
\ D is equivalent to [^ 0-9]
\ W is equivalent to [A-Za-z_0-9]
\ W is equivalent to [^ A-Za-z_0-9].
Example 1:
System.out.println("15088688388".replaceAll("(\\d{3})(\\d{4})","$1****"));
\\ d {3} to 150, \\. 4 {D } is 8868, $ 1 for the first group, that is, \\ d {3} . The output 150 **** 8388
System.out.println("15088688388".replaceAll("(\\d{3})(\\d{4})","$1222"));输出1502228388
Example 2:
System.out.println("15088688388".replaceAll("\\d","b"));输出bbbbbbbbbbb
\ D represents a number, but in front of itself as containing \ therefore a need in front of \
System.out.println("15088688388".replaceAll("\\d+","b"));输出b,
+ Sign indicates one or more times, so the whole is replaced.
2.3 Variable string StringBuffer / StringBuilder
For example on a blog you have to verify the performance of both.
capacity> = length of space.
Exemplified StringBuffer string variable.
public class StringBufferReferenceTest {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("123");
StringBuffer sb2 = sb1;
sb1.append("2222");
System.out.println(sb1);
System.out.println(sb2); //sb1 和 sb2还是指向同一个内存的
}
}
输出:
1232222
1232222
Examples of common functions
public class StringBuffertest {
public static void main(String[] args) {
// TODO 自动生成的方法存根
StringBuffer sb1 = new StringBuffer("123");
sb1.append("12");//12312
System.out.println(sb1);
sb1.insert(2,"haha");//在第二个字符后面插入12haha12
System.out.println(sb1);
sb1.delete(2,3);//删除第2~3个字符,含尾不含头
System.out.println(sb1);
sb1.replace(2,5,"222");//替换第2~5个字符(第3,4,5),含尾不含头
System.out.println(sb1);
String s1=sb1.substring(3,6);//截取3~6个字符(第4,5,6),原字符串不变
System.out.println(s1);
System.out.println(sb1);
}
}
输出:
12312
12haha312
12aha312
12222312
223
12222312
Third, the time classes
3.1Calendar
For example:
Acquisition time, day of the week when the moment to calculate the last day of each month, set the date, and modification date
import java.util.Calendar;
public class CalendarTest {
Calendar calendar = Calendar.getInstance();
public void test1() {
// 获取年
int year = calendar.get(Calendar.YEAR);
// 获取月,这里需要需要月份的范围为0~11,因此获取月份的时候需要+1才是当前月份值
int month = calendar.get(Calendar.MONTH) + 1;
// 获取日
int day = calendar.get(Calendar.DAY_OF_MONTH);
// 获取时
int hour = calendar.get(Calendar.HOUR);
// int hour = calendar.get(Calendar.HOUR_OF_DAY); // 24小时表示
// 获取分
int minute = calendar.get(Calendar.MINUTE);
// 获取秒
int second = calendar.get(Calendar.SECOND);
// 星期,英语国家星期从星期日开始计算
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println("现在是" + year + "年" + month + "月" + day + "日" + hour
+ "时" + minute + "分" + second + "秒" + "星期" + weekday);
}
// 一年后的今天
public void test2() {
// 同理换成下个月的今天calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.YEAR, 1);
// 获取年
int year = calendar.get(Calendar.YEAR);
// 获取月
int month = calendar.get(Calendar.MONTH) + 1;
// 获取日
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("一年后的今天:" + year + "年" + month + "月" + day + "日");
}
// 获取任意一个月的最后一天
public void test3() {
// 假设求6月的最后一天
int currentMonth = 6;
// 先求出7月份的第一天,实际中这里6为外部传递进来的currentMonth变量
// 1
calendar.set(calendar.get(Calendar.YEAR), currentMonth, 1);
calendar.add(Calendar.DATE, -1);
// 获取日
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("6月份的最后一天为" + day + "号");
}
// 设置日期
public void test4() {
calendar.set(Calendar.YEAR, 2000);
System.out.println("现在是" + calendar.get(Calendar.YEAR) + "年");
calendar.set(2018, 7, 8);
// 获取年
int year = calendar.get(Calendar.YEAR);
// 获取月
int month = calendar.get(Calendar.MONTH)+1;
// 获取日
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("现在是" + year + "年" + month + "月" + day + "日");
}
//add和roll的区别,roll如果改变号,不会引起月的改变(不会改变上一级)。
public void test5() {
calendar.set(2018, 7, 8);
calendar.add(Calendar.DAY_OF_MONTH, -8);
// 获取年
int year = calendar.get(Calendar.YEAR);
// 获取月
int month = calendar.get(Calendar.MONTH)+1;
// 获取日
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("2018.8.8, 用add减少8天,现在是" + year + "." + month + "." + day);
calendar.set(2018, 7, 8);
calendar.roll(Calendar.DAY_OF_MONTH, -8);
// 获取年
year = calendar.get(Calendar.YEAR);
// 获取月
month = calendar.get(Calendar.MONTH)+1;
// 获取日
day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("2018.8.8, 用roll减少8天,现在是" + year + "." + month + "." + day);
}
public static void main(String[] args) {
CalendarTest c = new CalendarTest();
c.test1();
System.out.println("============");
c.test2();
System.out.println("============");
c.test3();
System.out.println("============");
c.test4();
System.out.println("============");
c.test5();
}
}
输出:
现在是2020年1月12日8时13分51秒星期1
============
一年后的今天:2021年1月12日
============
6月份的最后一天为30号
============
现在是2000年
现在是2018年8月8日
============
2018.8.8, 用add减少8天,现在是2018.7.31
2018.8.8, 用roll减少8天,现在是2018.8.31
Another Date, DateUtil, Duration, LocalDate, LocalTime other time-based control. You can learn more about.
Fourth, the format class
4.1 digital format DecimalFormat
# Indicates: Up; 0 means: only
Integer part is 0, # think integer does not exist, do not write; 0 do not think, but at least one write, write 0
Integer part # 0,0 and not an integer multiple of the processing section is consistent is to have several write how many
# Represents the fractional part up to a few, and there must be 0 for only a few
For example:
Scientific notation, the control integer, decimal digits, expressed as a percentage
import java.text.DecimalFormat;
public class DecimalFormaterRuleTest {
public static void main(String[]args){
DecimalFormat df1,df2;
System.out.println("整数部分为0的情况,0/#的区别");
// 整数部分为0 , #认为整数不存在,可不写; 0认为没有,但至少写一位,写0
df1 = new DecimalFormat("#.00");
df2 = new DecimalFormat("0.00");
System.out.println(df1.format(0.1)); // .10
System.out.println(df2.format(0.1)); // 0.10
System.out.println("小数部分0/#的区别");
//#代表最多有几位,0代表必须有且只能有几位
df1 = new DecimalFormat("0.00");
df2 = new DecimalFormat("0.##");
System.out.println(df1.format(0.1)); // 0.10
System.out.println(df2.format(0.1)); // 0.1
System.out.println(df1.format(0.006)); // 0.01
System.out.println(df2.format(0.006)); // 0.01
System.out.println("整数部分有多位");
//0和#对整数部分多位时的处理是一致的 就是有几位写多少位
df1 = new DecimalFormat("0.00");
df2 = new DecimalFormat("#.00");
System.out.println(df1.format(2)); // 2.00
System.out.println(df2.format(2)); // 2.00
System.out.println(df1.format(20)); // 20.00
System.out.println(df2.format(20)); // 20.00
System.out.println(df1.format(200)); // 200.00
System.out.println(df2.format(200)); // 200.00
double pi=3.1415927;//圆周率
//取一位整数
System.out.println(new DecimalFormat("0").format(pi));//3
//取一位整数和两位小数
System.out.println(new DecimalFormat("0.00").format(pi));//3.14
//取两位整数和三位小数,整数不足部分以0填补。
System.out.println(new DecimalFormat("00.000").format(pi));//03.142
//取所有整数部分
System.out.println(new DecimalFormat("#").format(pi));//3
//以百分比方式计数,并取两位小数
System.out.println(new DecimalFormat("#.##%").format(pi));//314.16%
long c=299792458;//光速
//显示为科学计数法,并取五位小数
System.out.println(new DecimalFormat("#.#####E0").format(c));//2.99792E8
//显示为两位整数的科学计数法,并取四位小数
System.out.println(new DecimalFormat("00.####E0").format(c));//29.9792E7
//每三位以逗号进行分隔。
System.out.println(new DecimalFormat(",###").format(c));//299,792,458
//将格式嵌入文本
System.out.println(new DecimalFormat("光速大小为每秒,###米").format(c)); //光速大小为每秒299,792,458米
}
}
输出:
整数部分为0的情况,0/#的区别
.10
0.10
小数部分0/#的区别
0.10
0.1
0.01
0.01
整数部分有多位
2.00
2.00
20.00
20.00
200.00
200.00
3
3.14
03.142
3
314.16%
2.99792E8
29.9792E7
299,792,458
光速大小为每秒299,792,458米
rounding. Look up value down hereinbefore a digital type
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class TwoDigitsTest {
public static void main(String[] args) {
double f = 111231.5585;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1); //111231.56
DecimalFormat df =new DecimalFormat("#.00");
String f2 = df.format(f);
System.out.println(f2); //111231.56
String f3 = String.format("%.2f",f);
System.out.println(f3); //111231.56
NumberFormat ddf1=NumberFormat.getInstance() ;
System.out.println(ddf1.getClass().getName());
ddf1.setMaximumFractionDigits(2);
String f4= ddf1.format(f) ;
System.out.println(f4); //111,231.56
}
}
输出:
111231.56
111231.56
111231.56
java.text.DecimalFormat
111,231.56
4.2 Formatting string
MessageFormat: string format, array format using the parameters, and
import java.text.MessageFormat;
public class MessageFormatTest {
public static void main(String[] args) {
String message = "{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}";
Object[] array = new Object[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q"};
String value = MessageFormat.format(message, array);
System.out.println(value);
message = "oh, {0,number,#.##} is a good number";
array = new Object[]{new Double(3.1415)};
value = MessageFormat.format(message, array);
System.out.println(value);
}
}
输出:
ABCDEFGHIJKLMNOPQ
oh, 3.14 is a good number
4.3 Time Format
4.3.1DateFormat
import java.text.DateFormat;
import java.util.Locale;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateTest {
public static void main(String[] args) {
String strDate = "2008-10-19 10:11:30.345" ;
// 准备第一个模板,从字符串中提取出日期数字
String pat1 = "yyyy-MM-dd HH:mm:ss.SSS" ;
// 准备第二个模板,将提取后的日期数字变为指定的格式
String pat2 = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒" ;
SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ; // 实例化模板对象
SimpleDateFormat sdf2 = new SimpleDateFormat(pat2) ; // 实例化模板对象
Date d = null ;
try{
d = sdf1.parse(strDate) ; // 将给定的字符串中的日期提取出来
}catch(Exception e){ // 如果提供的字符串格式有错误,则进行异常处理
e.printStackTrace() ; // 打印异常信息
}
System.out.println(sdf2.format(d)) ; // 将日期变为新的格式
Date date = new Date();
DateFormat df1 = DateFormat.getInstance();
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss EE");
DateFormat df3 = new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒 EE",Locale.CHINA);
DateFormat df4 = new SimpleDateFormat("dd-MMMM-yyyy hh:mm:ss EE",Locale.US);
DateFormat df5 = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df6 = new SimpleDateFormat("yyyy年MM月dd日");
System.out.println("-------将日期按不同格式进行输出-------");
System.out.println("按照java默认的日期格式:"+df1.format(date));
System.out.println("按照指定格式 yyyy-MM-dd hh:mm:ss EE,系统默认区域:"+df2.format(date));
System.out.println("按照指定格式 yyyy年MM月dd日 hh时mm分ss秒 EE,区域为中国:"+df3.format(date));
System.out.println("按照指定格式dd-MMMM-yyyy hh:mm:ss EE,区域为美国:"+df4.format(date));
System.out.println("按照指定格式 yyyy-MM-dd :"+df5.format(date));
System.out.println("按照指定格式 yyyy年MM月dd日 :"+df6.format(date));
}
}
输出:
2008年10月19日 10时11分30秒345毫秒
-------将日期按不同格式进行输出-------
按照java默认的日期格式:20-1-12 下午8:55
按照指定格式 yyyy-MM-dd hh:mm:ss EE,系统默认区域:2020-01-12 08:55:22 星期日
按照指定格式 yyyy年MM月dd日 hh时mm分ss秒 EE,区域为中国:2020年01月12日 08时55分22秒 星期日
按照指定格式dd-MMMM-yyyy hh:mm:ss EE,区域为美国:12-January-2020 08:55:22 Sun
按照指定格式 yyyy-MM-dd :2020-01-12
按照指定格式 yyyy年MM月dd日 :2020年01月12日
4.3.2LocalDate
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateFormatterTest {
public static void main(String[] args) {
//将字符串转化为时间
String dateStr= "2016年10月25日";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
LocalDate date= LocalDate.parse(dateStr, formatter);
System.out.println(date.getYear() + "-" + date.getMonthValue() + "-" + date.getDayOfMonth());
System.out.println("==========================");
//将日期转换为字符串输出
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm:ss");
String nowStr = now.format(format);
System.out.println(nowStr);
}
}
输出:
2016-10-25
==========================
2020年01月12日 08:45:27
Reference: China University mooc java core technology Chen Liangyu