简体   繁体   中英

Using printf to add zeros to an integer value

I am trying to add zeros to a number input by a user by using the printf() function. However, I am unsure of the syntax usage. Here is what I have so far:

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);

            }
    }

}

and here is an example of it being used:

input : java 023
output: java          023

(That works fine)

Now my problem is, in a case where a number is less than 3 characters I want to be able to append zeros in front to make it be a length of 3. Furthermore, that is what I am hopping to do with the if statement that finds how many zeros a number needs. I was thinking of using something like this to the printf() function: ("%0zerosRequiredd", num); however, I do not know how to use it in conjunction with what I already have: System.out.printf("%-10s %-10s%n" , word, num) . Any suggestions?

You can do something like this:

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

That will lead with however many zeros.

For your example, you can use:

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

If num is a float, use Float.parseFloat(num) , or better yet declare it as the correct type.

See below:

 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);
    }

Here is the output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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