繁体   English   中英

使用printf将零加到整数值

[英]Using printf to add zeros to an integer value

我试图通过使用printf()函数将零添加到用户输入的数字。 但是,我不确定语法用法。 这是我到目前为止的内容:

public class Solution {

    public static void main(String[] args) {
            Scanner reader = new Scanner(System.in);
            final int requiredNumLength = 3;
            // readign untill EOF
            while (reader.hasNext()){
                    // getting the word form the input as a string
                    String word = reader.next();
                    // getting the number from the input as an integer
                    int num = reader.nextInt();
                    int length = String.valueOf(num).length();
                            if (length < requiredNumLength){
                                    int zerosRequired = requiredNumLength - length;
                                    //System.out.println("required zeros: " + zerosRequired);
                            }
                    // print out the columns using the word and num variables
                    System.out.printf("%-10s  %-10s%n" , word, num);

            }
    }

}

这是一个正在使用的示例:

input : java 023
output: java          023

(很好)

现在我的问题是,在一个数字少于3个字符的情况下,我希望能够在前面附加零以使其长度为3。此外,这就是我希望对if语句进行的处理,查找一个数字需要多少个零。 我正在考虑对printf()函数使用类似的东西:( ("%0zerosRequiredd", num); 但是,我不知道如何将其与已经拥有的东西结合使用: System.out.printf("%-10s %-10s%n" , word, num) 有什么建议么?

您可以执行以下操作:

String formatted = String.format("%03d", num);

这将导致许多零。

例如,您可以使用:

System.out.printf("%-10s %03d" , word, Integer.parseInt(num));

如果num是浮点型,请使用Float.parseFloat(num) ,或者最好将其声明为正确的类型。

见下文:

 public static void main(String[] args){
    String word = "Word";

    int num = 5;
    System.out.printf("%-10s  %03d\n" , word, num);

    num = 55;
    System.out.printf("%-10s  %03d\n" , word, num);

    num = 555;
    System.out.printf("%-10s  %03d\n" , word, num);

    num = 5555;
    System.out.printf("%-10s  %03d\n" , word, num);

    num = 55555;
    System.out.printf("%-10s  %03d\n" , word, num);
    }

这是输出:

mike@switters:~/code/scratch$ javac Pf.java && java Pf
Word        005
Word        055
Word        555
Word        5555
Word        55555

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM