简体   繁体   English

Java 格式化输出

[英]Java formatting output

I am not experienced in Java at all and am using a text editor to write code so I can't see what the problem is (I am running from command line) I see the error and know what it is but I have no idea how to fix it我完全没有 Java 方面的经验,正在使用文本编辑器编写代码,所以我看不到问题是什么(我从命令行运行)我看到错误并知道它是什么,但我不知道如何要解决这个问题

System.out.print(String.format("%7d", Math.pow(n,2).toString()));

I also tried without the .toString() Basically if I print only n it works, but the power function gives me an error probably because of return types, but pow should return a double and the string format %7d is probably also double right?我也试过没有.toString()基本上如果我只打印 n 它可以工作,但是 power 函数给我一个错误可能是因为返回类型,但是 pow 应该返回一个双精度并且字符串格式 %7d 可能也是双精度的,对吗?

You are using wrong format specifier.. %d is used for integer.您使用了错误的格式说明符。 %d用于整数。

Math.pow() returns primitive double on which you cannot invoke toString() method. Math.pow()返回原始double ,您无法在其上调用toString()方法。

Try using %7s which is for String , and convert your primitive double value to Wrapper type : -尝试使用用于String %7s ,并将原始 double 值转换为Wrapper type :-

String.format("%7s", Double.valueOf(Math.pow(n,2)).toString())

But, you don't need to convert your argument to String , you can directly use double value with %f : -但是,您不需要将参数转换为String ,您可以直接将double value%f :-

String.format("%.3f", Math.pow(n,2));

You most likely want to use f instead of d without the toString .您很可能想在没有toString情况下使用f而不是d If you actually were able to do toString (as Quoi points out, you cannot do from a primitive), it would make it impossible to use Formatter s that expect the used Number object ( Double in your case).如果您实际上能够执行toString (正如 Quoi 指出的,您不能从原语执行),那么将无法使用期望使用的Number对象(在您的情况下为Double )的Formatter

This is the Formatter that String.format uses.这是String.format使用的Formatter程序。

Math#pow(double,double) returns primitive double value you can not call toString method. Math#pow(double,double)返回不能调用toString方法的原始双精度值。 Use f instead of d, and d is for a decimal integer.使用 f 代替 d,d 表示十进制整数。

 System.out.format("%7f", Math.pow(n,2));

Better start with Eclipse or any other editor to write code.最好从 Eclipse 或任何其他编辑器开始编写代码。

problem lies with toString method.问题在于toString方法。 You have given format specifier %7d that means integer .您已经给出了格式说明符%7d ,这意味着integer You can't print string in place of it.你不能打印字符串来代替它。

The Right Format for double is %f not %d so modify your code to: double 的正确格式是 %f 而不是 %d,因此将代码修改为:

 System.out.print(String.format("%7f",  Math.pow(n,2)));

see also : link另见: 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM