0
我有一個關於如何使用printf進行格式化的問題。我用printf 3次;每3次,我用printf完全一樣,用1s%10.2f%n1
。不知何故,我不認爲我的第三次使用printf正在工作。我怎樣才能解決這個問題?任何幫助將不勝感激。當我編譯並執行它,我得到這個:在Java中使用printf顯示信息
run:
Average Monthly Electricity Bill: 463.26
Average Monthly Electricity Price Per Kilowatt: 4.83
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '10.2f'
at java.util.Formatter.format(Formatter.java:2487)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at CO2FromElectricityTester.main(CO2FromElectricityTester.java:43)
CO2 Emissions from Electricity Usage in a 3 Month Period: 394.56000000000006Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
這裏是我寫的兩個文件:
CO2FromElectricityTester.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author timothylee
*/
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
double avgPricePerKilowatt = CO2.calcPricePerKilowatt(avgKilowattHours,
avgMonthlyCost);
double avgCO2Emission = CO2.calcCO2Emission(emissionFactor, months,
avgMonthlyCost, avgPricePerKilowatt);
///////////////// display results
System.out.printf("%1s%10.2f%n", "Average Monthly Electricity Bill: ",
avgMonthlyCost);
System.out.printf("%1s%10.2f%n", "Average Monthly Electricity Price Per "
+ "Kilowatt: ", avgPricePerKilowatt);
System.out.printf("%1s%10.2f%n", "CO2 Emissions from Electricity Usage "
+ "in a 3 Month Period: " + avgCO2Emission);
}
}
CO2FromElectricity.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author timothylee
*/
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'中,您不會傳遞方法應該從中格式化字符串的參數。您將'avgCO2Emission'附加到格式字符串,而不是將其作爲單獨的參數傳遞。 – Vulcan