'Print at a specific location in java output stream
String s1= "SAM";
int x=30;
System.out.printf(s1); // prints at left most
s1=String.format("%03d",x);// formatting a number by 3 digits
System.out.printf("%15s",s1);//padding by 15 digits
System.out.println();
the task is to print the string and number in correct padding i.e whatever the length of string the number should start at 16th position. thanks in advance.
Solution 1:[1]
you can use the following template to achieve the result
String Wrd = "SPKJ";
int intVAlFor = 35;
String Vn = "";
if(Wrd.length()<= 15){
Vn = String.format("%0"+ (15 - Wrd.length() )+"d%s",0 ,Wrd);
Vn = Vn + Integer.toString(intVAlFor);
} else {
Vn = Wrd.substring(0, 15);
Vn = Vn + Integer.toString(intVAlFor);
}
System.out.println(Vn);
Output :
00000000000SPKJ35
You can change the formatting respective to formatting you want to use (Right Padding / Left Padding by making changes in String.format())
Solution 2:[2]
Your example is already padded by 13 spaces, so the number is at 16th position. So I thought you might want to padded by 15 in between of them. So the easiest is to use an empty string like following:
String s = "SAM";
int x = 30;
System.out.printf(s); //Prints at the most left
s = String.format("%03d", x); //Format the number by 3 digits
System.out.printf("%15s%s", "", s); //Padded by 15 digits
System.out.println();
SAM 030
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ajay Ganvir |
| Solution 2 |
