Java Output Format

本文解析了一道Hackerrank编程题目,并详细介绍了使用Java进行字符串和整数格式化输出的方法。通过具体代码示例展示了如何实现左对齐的字符串输出以及整数的前导零填充,确保输出格式符合题目要求。

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

Note:这些内容都是来自hackerrank的题目笔记和讨论区。

先看这道题的解法:

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(); //get strings
            int x=sc.nextInt();  //get integers
            //Complete this line
            System.out.printf("%-15s%03d%n",s1,x);

        }
        System.out.println("================================");

}

}

题目要求: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.
每行都得要15个characters,数字最多三位,不够的在前面补充0

这是一种解法:
System.out.printf(“%-15s%03d %n”,s1,x);

Explanations: %-15s : left justify 15: Total 15 characters of strig right from begining s: for string
%03d
03: Will pad 0 to left if number is less than 3 digit d: for integer
%n : for new line

补充的格式输出:
http://www.cnblogs.com/huhx/p/javaFormatter.html#formatter_introduce

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值