我有一個關於如何使用和顯示數組列表的問題。在我的情況下,我認爲我正確使用數組列表,因爲編譯器沒有抱怨。但是當我顯示它時,出現如下錯誤:Java顯示和使用數組列表
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;
}
}
什麼是72行? –
您試圖使用printf打印一個列表,說格式是浮點型,不兼容類型 – nachokk