第二章 格式化
格式化 重点
String.format("",...);
//格式化返回字符串
//%s %S %d
String.out.printf();
//格式化输出
字符 | 含义 |
---|---|
%s %S | 字符串s小字,S大写 |
%x %X | 十六进制整数 |
%d | 十进制整数 |
%o | 八进制整数 |
%c | 字符类型 |
%b | boolean类型 |
%f | 浮点数 |
%n %% | 换行,百分号 |
%tF | %tH:%<tM:%<tS |
%tT | %tY年%<tm月%<td日 %<tp %<tA %<ta %<tb %<tB |
标识 | 说明 |
---|---|
+ | 使得正数表示出正号,负数加不加无所谓,都可以表示出负号 |
- | 左对齐,不够位数的地方补上空格 |
0 | 在数字位数不够的地方补上0 |
空格 | 在位数不够的地方补上空格 |
, | 对数字分组,三位一隔,只可以用于十进制 |
( | 使用括号将去掉负号的负数包含进来 |
# | 让十六进制的数字加上ox,八进制的数字加上o;辅助%x和%o的使用,相当于一种对数字进制的补充说明提示 |
< | 格式化前一个转换符所描述的参数 |
1、掌握String.format() 或 System.out.printf()格式化输出方法
package cn.practice;
public class Format {
public static void main(String[] args) {
//+号的用法
//String str;
String str = String.format("数字的正负表示:%+d %d %+d %d",8,8,-8,-8);
System.out.println(str);//数字的正负表示:+8 8 -8 -8
//-的用法
str = String.format("左对齐:%-6d",8);
System.out.println(str);//左对齐:8
//0的用法
str = String.format("缺位补零:%06d",8);
System.out.println(str);//缺位补零:000008
//' '空格的用法
str = String.format("缺位补空格:% 6d",8);
System.out.println(str);//缺位补空格: 8
str = String.format("缺位补空格:% 6d",-8);
System.out.println(str);//缺位补空格: -8
//,的用法
str = String.format("数字分组:%,d",123456789);
System.out.println(str);//数字分组:123,456,789
//(的用法
str = String.format("括号用法:%(d",-8888);
System.out.println(str);//括号用法:(8888)
str = String.format("括号用法:%(d",8888);
System.out.println(str);//括号用法:8888
//#的用法
str = String.format("#括号用法(十六进制):%#x",12);
System.out.println(str);//#括号用法(十六进制):0xc
str = String.format("#括号用法(八进制):%#o",12);
System.out.println(str);//#括号用法(八进制):014
//<的用法
str = String.format("<括号用法:%f %<3.1f",3.14,3.2);
//"%<3.1f"作用的对象是前一个"%f"所作用的对象
System.out.println(str);//<括号用法:3.140000 3.1
}
}
package cn.practice;
public class FormatString {
public static void main(String[] args) {
String name = "张三丰";
int age = 19;
String address="河南省郑州科学大道33号";
String str1 = "姓名:" + name + ",年龄:" + age + "岁,家庭地址:" + address + "。";
System.out.println(str1);
//格式化字符串
String str2 = String.format("姓名:%s,年龄:%d岁,家庭地址:%s。",name,age,address);
System.out.println(str2);
//printf()格式直接输出
System.out.printf("姓名:%s,年龄:%d岁,家庭地址:%s。",name,age,address);
//格式化小数 float double
double num = Math.random();
System.out.println(num);
System.out.printf("%.1f %<.2f %<.3f %<.4f %<.0f%n",num);
System.out.printf("%.1f %2$.2f %1$.3f %<.4f %<.0f%n", num, 1.34245);
//格式化日期 < %tF 2023-02-10 %tT 09:43:22
System.out.printf("%tF %<tT %<tc%n",System.currentTimeMillis());
//tm 月 tM 分钟 年月日 tp上午 ta星期 tb月份
System.out.printf("%tY年%<tm月%<td日 %<tp %<tA %<ta %<tb %<tB%n",System.currentTimeMillis());
//时分秒
System.out.printf("%tH:%<tM:%<tS%n",System.currentTimeMillis());
//格式化整数
System.out.printf("%d %<05d %<5d%n", 123);
System.out.printf("%10s %25S %<-30s%n", "java", "hello,java");
System.out.printf("%10s", "java");
System.out.printf("%25S%n","hello,java");
System.out.printf("%-30s","hello,java");
System.out.printf("%-30s","h");
System.out.printf("%-30s%n","e");
System.out.println("李四");
System.out.println("李四丰");
System.out.println("李丰");
System.out.printf("%3s%n", "李四");
System.out.printf("%3s%n", "李四丰");
System.out.printf("%3s%n", "李丰");
}
}
2、了解格式化数字
百分比
小数位
货币符号
千分位
格式化数字 了解
NumberFormat
java.text.NumberFormat
package cn.practice;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
/**
* <p>Description:格式化数字 了解</p>
* <p>Class:java.text.NumberFormat</p>
* <p>Powered by zxy On 2023-04-10 15:50 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class FormatNumber01 {
public static void main(String[] args) throws ParseException {
int price = 18;
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
System.out.println(nf.format(18));
//输出:¥18.00
nf = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(nf.format(price));
//输出:$18.00
nf = NumberFormat.getCurrencyInstance(Locale.GERMAN);
System.out.println(nf.format(price));
//输出:18,00 ¤
String str = "18,00 ¤";
Number n1 = nf.parse(str);
Number n = nf.parse(nf.format(price));
System.out.println(n.doubleValue());
System.out.println(n1.doubleValue());
//输出 18.0
double d = 0.5;
nf = NumberFormat.getPercentInstance(Locale.CHINA);
System.out.println(nf.format(d));
//50%
}
}
package cn.practice;
import java.text.NumberFormat;
import java.util.Locale;
/**
* <p>Description:格式化货币</p>
* <p>Class:FormatNumber02</p>
* <p>Powered by zxy On 2023-04-10 20:01 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class FormatNumber02 {
public static void main(String[] args) {
int a = 1424248;
float b = .5F;
int c = 3;
System.out.printf("%03d %d %.3f%n", c, a, b);
//003 1424248 0.500
//格式化货币
NumberFormat nf1 = NumberFormat.getCurrencyInstance();
nf1.setMinimumFractionDigits(5);
System.out.println(nf1.format(a));
//¥1,424,248.00000
NumberFormat nf2 = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(nf2.format(a));
//$1,424,248.00
int n1 = 0;
int n2 = 0;
//创建一个数值格式化对象
NumberFormat nf = NumberFormat.getInstance();
//设置精确到小数点后2位
nf.setMaximumFractionDigits(2);
String res1;
if(n2 == 0){
//除数不能为0
res1 = "0";
}else{
res1 = nf.format((float) n1 / (float) n2 * 100);
}
System.out.println("百分比为:" + res1 + "%");
//百分比为:0%
}
}
DecimalFormat类
java.text.DecimalFormat
DecimalFormat 类是NumberFormat 十进制数字格式的具体子类。旨在解析和格式化任何语
言环境中的数字,包括支持西方、阿拉伯语和印度语数字。
支持不同类型的数字,包括整数(123)、定点数(123.4)、科学计数法(1.23E4),百分比
(12%)和货币金额(123美元)。
DecimalFormat();
//使用默认语言环境的默认模式和符号创建对象。其中隐含设置了三个数一组,若调用该方法如123456.789->123,456.789
DecimalFormat(String pattern);
//使用给定模式和默认语言环境的符号创建对象。
DecimalFormat(String pattern, DecimalFormatSymbols symbols);
//使用给定的模式和符号创建对象
//pattern - 非本地化的模式字符串
//symbols - 要使用的符号集
package cn.practice;
import java.text.DecimalFormat;
/**
* <p>Description:整数(123)、定点数(123.4)、科学计数法(1.23E4),百分比</p>
* <p>Class:DecimalFormat</p>
* <p>Powered by zxy On 2023-04-10 20:26 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class DecimalFormat01 {
public static void main(String[] args) {
double d=156.22359646;
System.out.println(new DecimalFormat("0").format(d));
//156-被格式化的数值位数够,则取所有整数
System.out.println(new DecimalFormat("#").format(d));
//156-被格式化的数值位数够,则取所有整数
System.out.println(new DecimalFormat("00000.###").format(d));
//00156.224-被格式化的数值位数不够,则整数位不够的补零
System.out.println(new DecimalFormat("#.######\u2030").format(d));
System.out.println(new DecimalFormat("#.######‰").format(d));
//156223.59646‰-以千分比方式计数并且保留6位小数
System.out.println(new DecimalFormat("#.##%").format(d));
//15622.36%-以百分比方式计数并且保留2位小数
long c=4673568;
System.out.println(new DecimalFormat("#.#####E00").format(c));
//4.67357E06-显示为科学计算法,并保留5为小数且被格式化的数值位数不够,不够的补零
System.out.println(new DecimalFormat("00.####E0").format(c));
//46.7357E5-显示为科学计数法,并保留2位整数,4位小数
System.out.println(new DecimalFormat("####,###").format(c));
//4,673,568-毎三位用逗号分隔
System.out.println(new DecimalFormat("数据分隔后为,##大小").format(c));
//数据分隔后为4,67,35,68大小
}
}
package cn.practice;
import java.text.NumberFormat;
import java.util.Locale;
/**
* <p>Description:格式化百分比、货币、千分位</p>
* <p>Class:DecimalFormat02</p>
* <p>Powered by zxy On 2023-04-10 20:42 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class DecimalFormat02 {
public static void main(String[] args) {
//格式化百分比
double d = Math.random();
System.out.println(d);//0.012607079852532954
System.out.printf("格式化:%.2f%n", d);//格式化:0.01
NumberFormat nf = NumberFormat.getPercentInstance();
System.out.println("百分比:" + nf.format(d));//百分比:1%
//格式化加小数
nf.setMinimumFractionDigits(2);
System.out.println("百分比:" + nf.format(d));//百分比:1.26%
//格式化货币
double money = 2342120.1268;
System.out.println(money);//2342120.1268
NumberFormat nffus = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(nffus.format(money));//$2,342,120.13
NumberFormat nffcn = NumberFormat.getCurrencyInstance(Locale.CHINA);
nffcn.setMaximumFractionDigits(1);
System.out.println(nffcn.format(money));//¥2,342,120.1
System.out.printf("¥%.2f%n", money);//¥2342120.13
//格式化千分位
long n = 2421482839492L;
double nn = Math.random();
NumberFormat nf3 = NumberFormat.getNumberInstance();
System.out.println(nf3.format(n));//2,421,482,839,492
System.out.println(nn);//0.8236233035550812
nf3.setMinimumFractionDigits(4);
System.out.println(nf3.format(nn));//0.8236
System.out.printf("%.4f%n", nn);//0.8236
}
}
3、掌握日期对象的格式化方法
格式化日期
String.format()
package cn.practice;
import java.time.LocalDate;
import java.util.Date;
/**
* <p>Description:**格式化日期**</p>
* <p>Class:DateFormat</p>
* <p>Powered by zxy On 2023-04-10 20:53 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class DateFormat01 {
public static void main(String[] args) {
Date d1 = new Date();
System.out.printf("%tY年%<tm月%<td日 %<ta %<tA %n", d1);
System.out.printf("%tA%n", System.currentTimeMillis());
System.out.printf("%tA", LocalDate.of(2000, 5, 1));
}
}
转换符 | 说明 | 结果 |
---|---|---|
%tH | 小时(00~23) | 15 |
%tk | 小时(0~23) | 15 |
%tM | 分钟(00~59) | 35 |
%tl | 小时(1~12) | 3 |
%tL | 毫秒(000~999) | 923 |
%tN | 9位数微秒(000000000-999999999) | 923000000 |
%tp | 当前语言环境下上午/下午 | 下午 |
%tz | 时区 | +0800 |
%tZ | 时区 | CST |
%tQ | 从1970-01-01 00:00:00到现在的毫秒 | 1526196955923 |
%ts | 从1970-01-01 00:00:00到现在的秒 | 1526196955 |
%tS | 秒(00~59) | 55 |
%tF | 年-月-日 | 2022-02-11 |
%tD | 月/日/年 | 02/11/22 |
%tc | 全部时间日期 | 星期六 二月 11 15:44:21 CST 2022 |
%tr | 时分秒PM | 10:05:00 下午 |
%tT | 时分秒 | 10:05:00 |
%tR | 时分 | 10:05 |
SimpleDateFormat
import java.text.SimpleDateFormat;
字母 | 日期或时间元素 | 表示 | 示例 |
---|---|---|---|
G | Era标志符 | Text | AD |
y | 年 | Year | 1996;96 |
M | 年中的月份 | Month | July;Jul;07 |
w | 年中的周数 | Number | 27 |
W | 月份中的周数 | Number | 2 |
D | 年中的天数 | Number | 189 |
d | 月份中的天数 | Number | 10 |
F | 月份中的星期 | Number | 2 |
E | 星期中的天数 | Text | Tuesday,Tue |
a | Am/pm标记 | Text | PM |
H | 一天中的小时数(0-23) | Number | 0 |
k | 一天中的小时数(1-24) | Number | 24 |
K | am/pm中的小时数(0-11) | Number | 0 |
h | am/pm中的小时数(1-12) | Number | 12 |
m | 小时中的分钟数 | Number | 30 |
s | 分钟中的秒数 | Number | 55 |
S | 毫秒数 | Number | 978 |
z | 时区 | General time zone | Pacific Standard Time;PST;GMT-08:00 |
Z | 时区 | RFC 822 time zone | -0800 |
package cn.practice;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
/**
* <p>Description:格式化日期</p>
* <p>Class:SimpleDateFormat</p>
* <p>Powered by zxy On 2023-04-10 20:57 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class SimpleDateFormat1 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//java.util.Date()
Date d = new Date();
System.out.println(sdf.format(d));//2023-04-10 20:58:57
// 指定格式化格式
var f = new SimpleDateFormat("今天是 " + "yyyy 年 MM 月 dd 日 E HH 点 mm 分 ss 秒");
Date now = new Date();
System.out.println(f.format(now)); // 将当前时间袼式化为指定的格式
//今天是 2023 年 04 月 10 日 周一 20 点 58 分 57 秒
//Date 对象 格式化
Date d1 = new Date();
System.out.printf("%tF %<tT %<Ta %<tA %<tb %<tB %<tp%n", d1);
//2023-04-10 20:58:57 周一 星期一 4月 四月 下午
System.out.printf("%tH %<tM %<tS%n", d1);
//20 58 57
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
String str = sdf1.format(d1);
System.out.println(str);//2023-04-10 20:58:57
System.out.println(sdf2.format(d1));//20230410205857
var sd1 = new SimpleDateFormat("MM月dd日 E a M");
System.out.println(sd1.format(d1));
//04月10日 周一 下午 4
//请输出今日日期格式为 2020年12月12日 22:33:33 星期几
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss E");
System.out.println(sdf3.format(d));//2023年04月10日 20:58:57 周一
//java.time.DateTimeFormatter
LocalDate d11 = LocalDate.now();
DateTimeFormatter df1 = DateTimeFormatter.ofPattern("yyyy.MM.dd E");
System.out.println(d11.format(df1));//2023.04.10 周一
LocalDateTime d2 = LocalDateTime.now();
System.out.println(d2);//2023-04-10T20:58:57.360631200
System.out.printf("%tF %<tT%n", d2);//2023-04-10 20:58:57
System.out.println(d2.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss E ")));
//2023年04月10日 20:58:57 周一
System.out.println(d2.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
//20230410205857
}
}
随机(了解)
Math.random() 随机小数double
java.util.Random随机类
package cn.practice;
public class Random1 {
public static void main(String[] args) {
//1 java.lang.Math random()方法-------------------------
for (int i = 0; i < 5; i++) {
//java.lang.Math类年 random()方法,是返回大于0 小于1的随机小数(double)
System.out.println(Math.random());
}
//随机布尔
boolean f = Math.random() > .5;
System.out.println(f);
//有10个学生,随机抽一个幸运学生 数组下载是10 0 - 9
var sts = new String[]{"李四", "张三", "李丽丽", "张三丰", "赵六", "李勇", "王五", "周强", "郑国", "赵飞飞"};
//利用Math.random() 随机小数 ,Math.round() 方法,获取随机范围数字 0 - 9
int index = (int)Math.round(Math.random()*9);
//0.000001 * 9 = 0.00009 四舍五入取整 0
//0.999999 * 9
//System.out.println(.999*9);
System.out.println(sts.length);
System.out.printf("幸运学生:%s%n",sts[index]);
//1 四舍五入取整数,返回long类型的整数
System.out.println(Math.round(.555));
//0
System.out.println(Math.round(.444));
//0
System.out.println(Math.round(.111));
//0
System.out.println(Math.round(.009));
//1
System.out.println(Math.round(1.2));
}
}
java.util.UUID 唯一随机ID 是个字符串
雪花算法(SnowFlake)随机long id snowflake
package cn.practice;
import java.util.Random;
import java.util.UUID;
/**
* <p>Description:</p>
* <p>Class:Random</p>
* <p>Powered by zxy On 2023-04-10 21:50 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class Random2 {
public static void main(String[] args) {
System.out.println(System.getProperty("java.version"));//17.0.6
//java.util.Date Calendar Scanner
//java.util.Random java.util java官方的工具包
//(1)实例化
Random rand = new Random();
//(2)使用
System.out.println(rand.nextBoolean());//true
System.out.println(rand.nextDouble());//0.17502483606452768
System.out.println(rand.nextDouble(5));//2.404493828880103
System.out.println(rand.nextDouble(5,10));//8.086035542378285
//0-5 不包含5,之间的随机整数0 -4
System.out.println(rand.nextInt(5));//0
//1-100 的随机整数
System.out.println(rand.nextInt(1,101));//36
//利用循环语句,特殊5次,获取并输出5个随机整数(1-2)
for (int i = 0; i < 5; i++) {
System.out.println(rand.nextInt(1,3));
}
//3 UUID -------------------------
UUID.randomUUID(); //最常用
System.out.println(UUID.randomUUID().toString());
//27720047-f27e-4ebc-a0f6-3189c8c48d8c
System.out.println(UUID.fromString("095c64fe-c5bf-11ea-aec6-a402b9e2b04d"));
//095c64fe-c5bf-11ea-aec6-a402b9e2b04d
System.out.println(UUID.nameUUIDFromBytes("身份证号码".getBytes()));
//84e0cb5d-57ed-395b-8cc0-4b4ab9a7997b
}
}
生成1-100之间的随机整数?
package cn.practice;
import java.util.Random;
public class RandomInt {
public static void main(String[] args) {
//生成1-100之间的随机整数?
Random rand = new Random();
int number = rand.nextInt(1,101);
//(0-99) + 1
int number1 =rand.nextInt(100) + 1;
System.out.println(number);
System.out.println(number1);
}
}
4、使用随机编写一个中奖30%的案例
package cn.practice;
import java.util.Random;
/**
* <p>Description:实现一个抽奖效果,中奖率为30%</p>
* <p>Class:Random</p>
* <p>Powered by zxy On 2023-04-10 22:00 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class WinaPrize30 {
public static void main(String[] args) {
//实现一个抽奖效果,中奖率为30%
Random rand = new Random();
int ok = rand.nextInt(1, 101);
if (ok <= 30) {
System.out.println("恭喜,你中奖了," + ok);
} else {
System.err.println("遗憾,未中奖.");
}
}
}
4、使用随机编写一个中奖30%的案例
package cn.practice;
import java.util.Random;
/**
* <p>Description:实现一个抽奖效果,中奖率为30%</p>
* <p>Class:Random</p>
* <p>Powered by zxy On 2023-04-10 22:00 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class WinaPrize30 {
public static void main(String[] args) {
//实现一个抽奖效果,中奖率为30%
Random rand = new Random();
int ok = rand.nextInt(1, 101);
if (ok <= 30) {
System.out.println("恭喜,你中奖了," + ok);
} else {
System.err.println("遗憾,未中奖.");
}
}
}
5、随机生成2023-1-1 0:0:0 到 现在的随机日期10个?
package cn.practice;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
/**
* <p>Description:随机生成2023-1-1 0:0:0 到 现在的随机日期10个?</p>
* <p>Class:RandomDate</p>
* <p>Powered by zxy On 2023-04-11 11:27 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class RandomDate {
public static void main(String[] args) throws ParseException {
//方法一
Calendar c = Calendar.getInstance();
c.set(2023,0,1,0,0,0);
long ss = c.getTimeInMillis();
long nn = System.currentTimeMillis();
System.out.printf("10个 %tF %<tT 到 %tF %<tT之间的随机日期%n",ss,nn);
for (int i = 10;i>0;i--){
long t=Math.round(Math.random()*(nn-ss))+ss;
System.out.printf("%tF %<tT%n",t);
}
System.out.println("-----------");
//方法二
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date start = sdf.parse("2023-1-1 00:00:00");
System.out.println(start.getTime());
System.out.printf("%tF %<tT%n",start);
System.out.printf("%tF %<tT%n",System.currentTimeMillis());
Random rand = new Random();
System.out.printf("10个 %tF %<tT 到 %tF %<tT之间的随机日期%n",start,System.currentTimeMillis());
for (int i = 10;i>0;i--){
long l= rand.nextLong(start.getTime(),System.currentTimeMillis()+1);
System.out.printf("%tF %<tT%n",l);
}
}
}