Java 更改printf()方法中的格式说明符会导致IllegalFormatFlagsException
在下面的代码中,将Java 更改printf()方法中的格式说明符会导致IllegalFormatFlagsException,java,methods,format,printf,Java,Methods,Format,Printf,在下面的代码中,将printf()方法中的格式说明符从%04d%n更改为%0-4d%n后,运行代码将导致 线程“main”java.util.IllegalFormatFlagsException中的异常: 标志='-0' 完整的源代码如下所示: public class MinArray { public static void main(String[] args) { byte[] storeMinimum = new byte[5]; byte
printf()
方法中的格式说明符从%04d%n
更改为%0-4d%n
后,运行代码将导致
线程“main”java.util.IllegalFormatFlagsException中的异常:
标志='-0'
完整的源代码如下所示:
public class MinArray {
public static void main(String[] args) {
byte[] storeMinimum = new byte[5];
byte[] trialArray = new byte[15];
for(byte bt=0; bt < storeMinimum.length; bt++){
randomize(trialArray);
storeMinimum[bt] = findMinimum(trialArray);
}
for (byte minValue : storeMinimum)
System.out.printf("%0-4d%n", minValue);
}
private static byte findMinimum(byte[] valArray) {
byte minValue = valArray[0];
for(byte bt=0; bt < valArray.length; bt++)
minValue = (byte) Math.min(minValue, valArray[bt]);
return minValue;
}
private static void randomize(byte[] valArray) {
for (byte bt = 0; bt < valArray.length; bt++)
valArray[bt] = (byte) (Math.random()*128);
}
}
public-class-MinArray{
公共静态void main(字符串[]args){
字节[]存储最小值=新字节[5];
字节[]trialArray=新字节[15];
用于(字节bt=0;bt
有人能解释一下,为什么会发生这种情况,因为我希望字节文字显示为左对齐,有4个字符的位置?另外,请确实为同样的问题提出一个解决方案。我想当你写信的时候
System.out.printf("%04d%n", minValue);
这是对的。左侧的所有空白将替换为“0”
“-”用于左对齐
它们不能一起使用。您可能正在搜索:
System.out.printf("%-4d%n", minValue);
此外:
整数格式
字符串格式
浮点点格式
我建议您研究一下这个答案:我发现printf()方法格式说明符中不能同时使用“0”和“-”。尽管如此,我必须承认我在任何地方都找不到明确的表述。
%d : will print the integer as it is.
%6d : will print the integer as it is. If the number of digits is less than 6, the output will be padded on the left.
%-6d : will print the integer as it is. If the number of digits is less than 6, the output will be padded on the right.
%06d : will print the integer as it is. If the number of digits is less than 6, the output will be padded on the left with zeroes.
%.2d : will print maximum 2 digits of the integer.
%s : will print the string as it is.
%15s : will print the string as it is. If the string has less than 15 characters, the output will be padded on the left.
%-6s : will print the string as it is. If the string has less than 6 characters, the output will be padded on the right.
%.8d : will print maximum 8 characters of the string.
%f : will print the number as it is.
%15f : will print the number as it is. If the number has less than 15 digits, the output will be padded on the left.
%.8f : will print maximum 8 decimal digits of the number.
%9.4f : will print maximum 4 decimal digits of the number. The output will occupy 9 characters at least. If the number of digits is not enough, it will be padded