gpt4 book ai didi

java - 检查数组中的整数是否在范围内

转载 作者:行者123 更新时间:2023-12-01 13:47:33 24 4
gpt4 key购买 nike

基本上,我要编写的程序是从客户那里获取 12 个月的能源使用情况,然后输出总使用量、两种费率的价格(公式包含在代码中)并说出哪种费率更便宜。但它还必须检查这 12 个月中每个月的输入是否在范围内(大于“0”且小于或等于“1000”)。我找到了一种相当简单(?)的方法来使用数组来做到这一点,但是我不知道如何检查该数组中扫描的每个整数是否实际上在 0 < int <= 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.");
}

}
}

最佳答案

将输入读取循环更改为如下所示:

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;
}

关于java - 检查数组中的整数是否在范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20248721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com