日期:2014-05-20  浏览次数:20682 次

有关格式控制输出的问题。
import   java.util.*;
public   class   example
{
public   static   void   main(String   args[])
{
Scanner   reader=new   Scanner(System.in);
int   x,y;
System.out.printf( "请输入一个数: ");
x=reader.nextInt();
if(x <0)
{
y=-1+2*x;
System.out.printf( "y=%3d "+y);
}
else   if(x==0)
{
y=-1;
System.out.printf( "y= "+y);
}
else
{
y=-1+3*x;
System.out.printf( "y= "+y);
}
}
}

运行后报错,知道是哪个%3d惹的,要怎么修改呢?把它怎样放才对?
请输入一个数:-6
y=Exception   in   thread   "main "   java.util.MissingFormatArgumentException:   Format   sp
ecifier   '3d '
                at   java.util.Formatter.format(Formatter.java:2429)
                at   java.io.PrintStream.format(PrintStream.java:899)
                at   java.io.PrintStream.printf(PrintStream.java:800)
                at   example.main(example.java:13)
Press   any   key   to   continue...

------解决方案--------------------
printf

public PrintStream printf(String format,
Object... args)

使用指定格式字符串和参数将格式化的字符串写入此输出流的便捷方法。

调用此方法的 out.printf(format, args) 形式,行为与以下调用完全相同:

out.format(format, args)

参数:
format - 在格式字符串的语法中描述的格式字符串
args - 格式字符串中的格式说明符引用的参数。如果参数多于格式说明符,则忽略额外的参数。参数的数量是可变的,并且可以为零。参数的最大数量受到《Java Virtual Machine Specification》定义的 Java 数组的最大维数的限制。针对 null 参数的行为依赖于 conversion。
返回:
此输出流
抛出:
IllegalFormatException - 如果格式字符串包含非法语法、与给定参数不兼容的格式说明符、对给定格式字符串而言不够充足的参数或其他非法条件。有关所有可能的格式错误的规范,请参阅 formatter 类规范的详细信息部分。
NullPointerException - 如果 format 为 null
从以下版本开始:
1.5

而你的代码中,其实是System.out.printf(String)!
应该是System.out.printf(String,Object...)!
把你的输出语句System.out.printf( "y=%3d "+y);改为System.out.printf( "y=%3d ",y);就可以了
下面的代码也一样改