String.Format用于舍入,无法定位非法格式转换源错误?

use*_*390 5 java string-formatting

我正在编写一个程序,让用户输入6个温度读数,然后是其中之一

  1. 返回最高原始值+ celcius版本
  2. 将原始值+转换返回到摄氏版本.

设置数组值的代码在这里:

System.out.print( "Enter Temperature:\t");   //Get the count...
        Temp = LocalInput.nextInt();
        WeatherSpots[K].CatchCount = Temp;
Run Code Online (Sandbox Code Playgroud)

我得到的错误信息是这个

java.util.IllegalFormatConversionException: f != java.lang.Integer
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printFloat(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)
at p2list.WeeklyReport(p2list.java:102)
at p2list.main(p2list.java:33)"
Run Code Online (Sandbox Code Playgroud)

我也找到了给我带来麻烦的确切短语:

String.format("%.2d", (WeatherSpots[K].CatchCount - 32) * 5 / 9)"
Run Code Online (Sandbox Code Playgroud)

我知道错误发生在我"%._"没有正确的说明符,但我的所有变量和数组都在int中,所以d应该工作

这是代码的其余部分:

这是我设置第一个数组的方式:

private static  WeatherLocation[] WeatherSpots = new WeatherLocation[6];"
Run Code Online (Sandbox Code Playgroud)

这是后来的数组使用的类

public class WeatherLocations extends WeatherLocation {
    public String LocationID;
    public Integer CatchCount;"

    arrays = WeatherSpots.LoccationID/Catchcount"
Run Code Online (Sandbox Code Playgroud)

catchcount是使用用户输入温度设置数组 的位置

int K;
for(K = 0 ; K < 6 ; K++){
    System.out.print( "Enter Temperature:\t");
    Temp = LocalInput.nextInt();
    WeatherSpots[K].CatchCount = Temp;
Run Code Online (Sandbox Code Playgroud)

这是我尝试调用WeatherSpots[K].catchcount值转换为celcius的方法

int K= 0;
for(K = 0 ; K < 6 ; K++){
    System.out.println( "" + WeatherSpots[K].LocationID +"\t\t" + WeatherSpots[K].CatchCount + "\t\t" + String.format("%.2f", (WeatherSpots[K].CatchCount - 32) * 5 / 9));
Run Code Online (Sandbox Code Playgroud)

如果我的数组和变量是正确的使用类型,会导致错误的原因是string.format什么?

Dan*_*her 8

String.format("%.2f", (WeatherSpots[K].CatchCount - 32) * 5 / 9)
Run Code Online (Sandbox Code Playgroud)

您正在尝试int使用doubles或floats 格式打印.这导致了IllegalFormatConversionException: f != java.lang.Integer.由于整数除法无论如何都会截断,因此打印小数点后两位的整数并不是很有用.只需除以浮点数9.0而不是int9即可得到可以格式化的浮点数%.2f.

在你的

String.format("%.2d", (WeatherSpots[K].CatchCount - 32) * 5 / 9)
Run Code Online (Sandbox Code Playgroud)

格式%.2d无效,因为用小数点后的位置打印整数是没有意义的.