【发布时间】:2014-01-01 16:26:12
【问题描述】:
我有一个关于如何使用和显示数组列表的问题。就我而言,我认为我正确使用了数组列表,因为编译器没有抱怨。但是当我显示它时,会出现一个如下所示的错误:
run:
Average Monthly Electricity Bill: 463.26
Exception in thread "main" java.util.IllegalFormatConversionException: f != java.util.ArrayList
Average Monthly Electricity Price Per Kilowatt: at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045)
at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2761)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2708)
at java.util.Formatter.format(Formatter.java:2488)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at CO2FromElectricityTester.main(CO2FromElectricityTester.java:72)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
我该如何解决这个问题?任何帮助将不胜感激。以下是我的代码:
public class CO2FromElectricityTester {
public static void main(String args[]){
// declare & initialize variables
double months = 3.0;
double emissionFactor = 1.37;
int kilowattHoursSept = 109;
int kilowattHoursOct = 87;
int kilowattHoursNov = 93;
double monthlyCostSept = 551.51;
double monthlyCostOct = 392.84;
double monthlyCostNov = 445.42;
double avgKilowattHours = (kilowattHoursSept + kilowattHoursOct +
kilowattHoursNov) / 3;
double avgMonthlyCost = (monthlyCostSept + monthlyCostOct +
monthlyCostNov) / 3;
// create object
CO2FromElectricity CO2 = new CO2FromElectricity();
// // // declare & initialize variables for methods
// // create array lists
ArrayList<Double> monthlyPriceForElec = new ArrayList<Double>();
ArrayList<Double> monthlyElectricBill = new ArrayList<Double>();
// average monthly price for electricity
double avgPricePerKilowatt = CO2.calcPricePerKilowatt(avgKilowattHours,
avgMonthlyCost);
// average monthly electric bill
double avgCO2Emission = CO2.calcCO2Emission(emissionFactor, months,
avgMonthlyCost, avgPricePerKilowatt);
// initialize array lists
monthlyPriceForElec.add(avgPricePerKilowatt);
monthlyElectricBill.add(avgCO2Emission);
// display results
System.out.printf("%1s%34.2f%n", "Average Monthly Electricity Bill: ",
avgMonthlyCost);
System.out.printf("%1s%20.2f%n", "Average Monthly Electricity Price Per "
+ "Kilowatt: ", monthlyPriceForElec);
System.out.printf("%1s%10.2f%n", "CO2 Emissions from Electricity Usage "
+ "in a 3 Month Period: ", monthlyElectricBill);
}
}
如果有帮助,下面是我声明方法的另一个文件:
public class CO2FromElectricity {
// default constructor
CO2FromElectricity(){
}
// method for calculating price per kilowatt
public double calcPricePerKilowatt(double kilowattHours, double monthlyCost){
return monthlyCost / kilowattHours;
}
// method for calculating CO2 emission
public double calcCO2Emission(double emissionFactor, double months,
double avgMonthlyCost, double avgPricePerKilowatt){
return (avgMonthlyCost / avgPricePerKilowatt) * emissionFactor * months;
}
}
【问题讨论】:
-
您正在尝试使用 printf 打印一个列表,说格式是浮点数,不兼容的类型