Java Output Formatting

本文详细介绍了printf函数的格式控制语法,包括对齐方式、填充字符、域宽和精度等设置,并通过一个Java示例展示了如何使用这些格式控制来美化输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

printf的格式控制的完整格式: 
%  -  0  m.n  l或h  格式字符 
下面对组成格式说明的各项加以说明: 
①%:表示格式说明的起始符号,不可缺少。 
②-:有-表示左对齐输出,如省略表示右对齐输出。 
③0:有0表示指定空位填0,如省略表示指定空位不填。 
④m.n:m指域宽,即对应的输出项在输出设备上所占的字符数。N指精度。用于说明输出的实型数的小数位数。为指定n时,隐含的精度为n=6位。 

⑤l或h:l对整型指long型,对实型指double型。h用于将整型的格式字符修正为short型。 


Sample Input

java 100
cpp 65
python 50

Sample Output

================================
java           100 
cpp            065 
python         050 
================================

Explanation

Each String is left-justified with trailing whitespace through the first  characters. The leading digit of the integer is the  character, and each integer that was less than  digits now has leading zeroes.


import java.util.Scanner;


public class Solution {


    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("================================");
            for(int i=0;i<3;i++)
            {
                String s1=sc.next();
                int x=sc.nextInt();
                //Complete this line
                System.out.printf("%-15s", s1);
                System.out.printf("%03d", x);
                System.out.println();
            }
            System.out.println("================================");


    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值