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?