线程"main" java.util.IllegalFormatConversionException中的异常:f !=



当运行这个程序时,我在命令行中遇到了这个问题,我只需要使用printf,并且需要总表面积和成本到小数点后2位

线程"main"java.util. illegalformatconverversionexception: f != java.lang.Stringjava.util.Formatter FormatSpecifier.failConversion美元(Formatter.java: 4302)java.util.Formatter FormatSpecifier.printFloat美元(Formatter.java: 2806)java.util.Formatter FormatSpecifier.print美元(Formatter.java: 2753)java.util.Formatter.format (Formatter.java: 2520)java.io.PrintStream.format (PrintStream.java: 970)java.io.PrintStream.printf (PrintStream.java: 871)MartianHouses.main (MartianHouses.java: 28)

import java.util.Scanner;
public class MartianHouses {
public static void main(String [] args) {
Scanner input = new Scanner(System.in); //create scanner
System.out.println("Enter the settles's name: "); // prompt user for name
String settlerName = input.nextLine(); //
System.out.println("Enter the length of a side of the house: ");
double oneSideOfHouse = input.nextInt();
double floorArea;
double roofArea;
double areaOfOuterWalls;
double totalSurfaceArea;
double costOfHouse;
if (oneSideOfHouse != 0) {
floorArea = (2 * (Math.pow(oneSideOfHouse, 2))) * (1 + (Math.pow(2, 0.5)));
roofArea = (2 * (Math.pow(oneSideOfHouse, 2))) * (1 + (Math.pow(2, 0.5)));
areaOfOuterWalls = 8 * 12 * oneSideOfHouse;
totalSurfaceArea = floorArea + areaOfOuterWalls + roofArea;
costOfHouse = 14.50 * totalSurfaceArea;
System.out.printf(settlerName + " has a house surface area of " + ("%.2f"), totalSurfaceArea + " and cost of " + ("%.2f), costOfHouse);
} 
}
}

属性顺序错误。试试以下命令:

Scanner input = new Scanner(System.in); //create scanner
System.out.println("Enter the settles's name: "); // prompt user for name
String settlerName = input.nextLine(); //
System.out.println("Enter the length of a side of the house: ");
double oneSideOfHouse = input.nextInt();
double floorArea;
double roofArea;
double areaOfOuterWalls;
double totalSurfaceArea;
double costOfHouse;
if (oneSideOfHouse != 0) {
floorArea = (2 * (Math.pow(oneSideOfHouse, 2))) * (1 + (Math.pow(2, 0.5)));
roofArea = (2 * (Math.pow(oneSideOfHouse, 2))) * (1 + (Math.pow(2, 0.5)));
areaOfOuterWalls = 8 * 12 * oneSideOfHouse;
totalSurfaceArea = floorArea + areaOfOuterWalls + roofArea;
costOfHouse = 14.50 * totalSurfaceArea;
System.out.printf(settlerName + " has a house surface area of " + ("%.2f") + " and cost of " + ("%.2f"), totalSurfaceArea, costOfHouse);
}

使用您的代码System.out.printf(settlerName + " has a house surface area of " + ("%.2f"), totalSurfaceArea + " and cost of " + ("%.2f"), costOfHouse);,您试图用前一个("%.2f")格式化第二个参数totalSurfaceArea + " and cost of " + ("%.2f"),因此出现错误。

相关内容

  • 没有找到相关文章

最新更新