[英]Calculate the total price of acquiring multiple cars - Java
这是我的代码:
double carsPrice = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of cars you would like to drive");
String [] numberOfCars = new String[sc.nextInt()];
while (numberOfCars.length > 5) {
System.out.println("Enter a number that is less than 5 and try again");
numberOfCars = new String[sc.nextInt()];
}
System.out.println("Enter the names of cars you would like to hire");
String [] chosenCarNames = new String[5];
sc.nextLine();
for (int i=0; i<numberOfCars.length; i++) {
int nameA = i+1;
System.out.println("Enter name of car " + nameA);
chosenCarNames [i] = sc.nextLine();
while ("lamborghini".equals(chosenCarNames[i]) && "toyota".equals(chosenCarNames[i]) && "audi 5".equals(chosenCarNames[i])) {
if (!"lamborghini".equals(chosenCarNames[i]) && !"toyota".equals(chosenCarNames[i]) && !"audi 5".equals(chosenCarNames[i])) {
System.out.println("Name of car " + nameA + " is invalid. Please try again");
chosenCarNames[i] = sc.nextLine();
}
}
}
if ("lamborghini".equals(chosenCarNames[i])) {
carsPrice = 59;
}
else if ("toyota".equals(chosenCarNames[i])) {
carsPrice = 49;
}
else {
carsPrice = 39;
}
我制作了一个 java 程序,要求客户输入他们想租用的汽车数量,然后该程序应允许用户根据他们想租用的汽车数量输入他们想租用的汽车的名称聘请。 我的问题是,如果客户想租用不止一辆车,我无法计算客户必须支付的总价。 如果客户只想租一辆车,我使用 if 语句来计算并显示客户必须支付的总金额
您可以将价格计算移动到循环中并累加它:
for (int i = 0; i < numberOfCars.length; i++) {
int nameA = i+1;
System.out.println("Enter name of car " + nameA);
chosenCarNames [i] = sc.nextLine();
// Input validation omitted for brevity
if ("lamborghini".equals(chosenCarNames[i])) {
carsPrice += 59;
}
else if ("toyota".equals(chosenCarNames[i])) {
carsPrice += 49;
}
else {
carsPrice += 39;
}
}
这是一些有趣的逻辑:
while ("lamborghini".equals(chosenCarNames[i]) && "toyota".equals(chosenCarNames[i]) && "audi 5".equals(chosenCarNames[i])) {
如果输入的值是“lamborghini”,那么第一部分就为真,但它怎么可能同时等于“toyota”和“audi”呢?
如果打算只允许“lamborghini”、“toyota”或“audi 5”,则将复合表达式 boolean 从内部if
语句移到while
循环中,并去掉内部if
:
System.out.println("Enter name of car " + nameA);
chosenCarNames [i] = sc.nextLine();
while (!"lamborghini".equals(chosenCarNames[i]) && !"toyota".equals(chosenCarNames[i]) && !"audi 5".equals(chosenCarNames[i])) {
System.out.println("Name of car " + nameA + " is invalid. Please try again");
chosenCarNames[i] = sc.nextLine();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.