一 格式化输出
1 点睛
常用的转换代码如下:
d:用于Java整型的十进制数。
f:浮动型。
s:字符串。
在%和转换代码之间可以插入一个整数来转换之后的值的宽度,即输出字符串的长度。默认情况下,转换后会在字符串的左边添加空格以达到需要的宽度(如果转换的字符串比设定宽度要长,宽度会被忽略)。在宽度之后可以插入一个小数点以及一个数值来指定转换后的double值保留的小数位数(精度)或是字符串String字符串所截取的长度。
格式字符串中的转换代码和对应参数的数据类型必须匹配,Java要求参数的数据类型和转换代码表示的数据类型必须相同。
2 printf() 格式化方式
数据类型 | 转换代码 | 举例 | 格式字符串举例 | 转换后输出的字符串 |
int | d | 512 | "%14d" "%-14d" | " 512" "512 " |
double | f e | 1595.1680010754388 | "14.2f" ".7f" "%14.4e" | " 1595.17" "1595.1680011" " 1.5952e+03" |
String | s | "Hello,World" | "%14s" "-14s" "%14.5s" | " Hello,World" "Hello,World " " Hello" |
3 实战
package Format;
import common.StdOut;
import common.StdRandom;
/**
* Copyright (C), 2020-2020, XXX有限公司
* FileName: RandomSeq
* Author: cakin
* Date: 2020/1/10
* Description: 格式化输出
*/
public class RandomSeq {
public static void main( String[] args ) {
int N = Integer.parseInt(args[0]);
double lo = Double.parseDouble(args[1]);
double hi = Double.parseDouble(args[2]);
for(int i=0;i<N;i++){
double x = StdRandom.uniform(lo,hi);
StdOut.printf("%.2f\n",x);
}
System.out.println("--------------------------");
System.out.printf("%14d\n",512);
System.out.printf("%-14d\n",512);
System.out.printf("%14.2f\n",1595.1680010754388);
System.out.printf("%.7f\n",1595.1680010754388);
System.out.printf("%14.4e\n",1595.1680010754388);
System.out.printf("%14s\n","Hello,World");
System.out.printf("%-14s\n","Hello,World");
System.out.printf("%14.5s\n","Hello,World");
}
}
4 测试
java RandomSeq 5 100.0 200.0
197.92
104.52
105.76
133.55
133.09
--------------------------
512
512
1595.17
1595.1680011
1.5952e+03
Hello,World
Hello,World
Hello
二 格式化输入
1 代码
package Format;
import common.StdIn;
import common.StdOut;
/**
* Copyright (C), 2020-2020, XXX有限公司
* FileName: Average
* Author: cakin
* Date: 2020/1/10
* Description: 格式化输入
*/
public class Average {
public static void main( String[] args ) {
double sum = 0.0;
int cnt = 0;
while(!StdIn.isEmpty()){
sum+=StdIn.readDouble();
cnt++;
}
double avg = sum /cnt;
StdOut.printf("Average is %.5f\n",avg);
}
}
2 输出
1.23456
2.24567
3.45678
4.34567
<ctrl+d>
Average is 2.31234
三 代码参考
https://gitee.com/cakin24/Algorithm/tree/master/src/main/java/Format