基本上,我应该写的程序是从客户获得12个月的能源使用量,然后输出总使用量,两个关税的价格(公式包含在代码中)并说明哪个关税更便宜。但它还必须检查这12个月中每一个的输入是否在该范围内(大于“0”且小于或等于“1000”)。 我已经找到了一种使用数组的相当简单(?)的方法,但是我不知道如何检查扫描到该数组中的每个整数是否实际上在0 <范围内。 int&lt; = 1000
如果整数小于0或大于1000,程序必须输出一行“请输入有效金额”并再次询问相同的整数,以便它不会存储错误的值,如果它有意义吗?
import java.util.Scanner;
public class EnergyConsumptionExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int total_usage;
float t1_cost, t2_cost;
final int MAX_USAGE = 1000, MIN_USAGE = 0;
int[] energyCons = new int[12];
for (int month = 0; month < energyCons.length; month++) {
System.out.print("Please enter the monthly kWh usage for month ");
System.out.print((month + 1) + ": ");
energyCons[month] = scan.nextInt();
}
int totalCons = 0;
for (int month = 0; month < energyCons.length; month++) {
totalCons += energyCons[month];
}
System.out.println();
System.out.println("Total usage for the year was " + totalCons + " kWh");
t1_cost = (float) (totalCons * 0.1);
t2_cost = (float) ((totalCons * 0.09) + 50);
System.out.println("Using tariff one, the cost is: " + t1_cost);
System.out.println("Using tariff two, the cost is: " + t2_cost);
System.out.println();
if (t1_cost > t2_cost) {
System.out.println("Tariff two would be cheaper for this customer.");
} else {
System.out.println("Tariff one would be cheaper for this customer.");
}
}
}
答案 0 :(得分:1)
将输入阅读循环更改为:
for (int month = 0; month < energyCons.length; month++) {
System.out.print("Please enter the monthly kWh usage for month ");
System.out.print((month + 1) + ": ");
int inputValue = scan.nextInt();
while (inputValue < 0 || inputValue > 1000) {
System.out.println("Please enter a valid amount: ");
inputValue = scan.nextInt();
}
energyCons[month] = inputValue;
}