是否可以在If语句中访问方法语句的结果?我正在编写一个程序来计算抄表任务。 Netbeans声明它无法找到我创建的methodName的符号。这是迄今为止的代码:
public class Meter_Utility {
//Begin Main Method
public static void main(String[] args) {
//new scanner object
Scanner input = new Scanner(System.in);//create new scanner object
//Declarations
double prevMeter;
double currMeter;
double rate = 0;
// double totalUsage = 0;
//obtain meter readings from user
System.out.print("Welcome to the City Power Bill Calculator! Please enter your previous meter reading: ");
prevMeter = input.nextDouble();
System.out.print("Please enter your Current meter reading: ");
currMeter = input.nextDouble();
//output total usage
System.out.printf("your usage was: %.1f KwHs", totalUsage(prevMeter, currMeter));
//calculate rate
if (totalUsage < 500) {
rate = .0809;
}
else if (totalUsage > 500 && totalUsage < 900){
rate = .091;
}
else {
rate = .091;
}
//output rate
System.out.printf("\nYour rate was: %.4f/KwH", rate);
} //End Main Method
/**
* Method to calculate total Usage
* @param u1
* @param u2
* @return difference of month 1 and month 2
*/
private static double totalUsage(double u1, double u2) {
return u2 - u1;
}
}
所以我希望在if语句中可以访问totalUsage,这样我就可以确定速率并继续。
我已经针对类似帖子研究了stackoverflow并且空了。我在这里研究过:对于if / else语句已经是: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
答案 0 :(得分:2)
您应该声明一个变量来存储您的总使用量,或者每次都调用该方法。
使用变量:
double totalUsage = totalUsage(prevMeter, currMeter);
System.out.printf("your usage was: %.1f KwHs", totalUsage);
//calculate rate
if (totalUsage < 500.0) {
rate = .0809;
}
else if (totalUsage > 500.0 && totalUsage < 900.0){
rate = .091;
}
else {
rate = .091;
}
//output rate
System.out.printf("\nYour rate was: %.4f/KwH", rate);
通过调用方法:
//output total usage
System.out.printf("your usage was: %.1f KwHs", totalUsage(prevMeter, currMeter));
//calculate rate
if (totalUsage(prevMeter, currMeter) < 500.0) {
rate = .0809;
}
else if (totalUsage(prevMeter, currMeter) > 500.0 && totalUsage(prevMeter, currMeter) < 900.0){
rate = .091;
}
else {
rate = .091;
}
//output rate
System.out.printf("\nYour rate was: %.4f/KwH", rate);