在java输出流中的特定位置打印


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

任务是用正确的填充打印字符串和数字即,无论字符串的长度如何,数字都应该从第16位开始。提前谢谢。

有关格式字符串语法,请参阅javadoc

为了使字符串左对齐,您需要使用%-15s。如果s1长于15个字符,则需要缩短它

String s1 = "antidisestablishmentarianism";
int len = s1.length();
if (len > 15) {
s1 = s1.substring(0, 15);
}
System.out.printf("%-15s%03d%n", s1, len);

运行上面的代码将打印以下内容。

antidisestablis028

并在你的问题中使用这个例子。

String s1 = "SAM";
int len = s1.length();
if (len > 15) {
s1 = s1.substring(0, 15);
}
int x = 30;
System.out.printf("%-15s%03d%n", s1, x);

输出为

SAM            030

您可以使用以下模板来实现结果

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

输出:

00000000000SPKJ35

您可以根据要使用的格式更改格式(通过在String.format()中进行更改,右填充/左填充(

您的示例已经填充了13个空格,因此数字位于第16位。所以我想你可能想在它们之间加15。所以最简单的方法是使用如下空字符串:

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