Java车辆租赁系统数组无法打印首个元素 仅输出最后一次输入值
问题根因
- 赋值逻辑错误:处理用户第i次输入的车型时,你嵌套了遍历整个
vehicleRentedArry的j循环,会把数组所有位置的元素都覆盖为当前输入的车型。比如你输入2辆车,第一次输入Car时,数组下标0、1都会被设为Car;第二次输入Trailer时,数组下标0、1又会被全部覆盖为Trailer,最终数组中所有元素都是最后一次输入的车型,所以打印时全是Trailer。 - 打印逻辑不符合要求:当前打印每次都调用
println自动换行,且没有做首行和后续行的格式区分,无法实现首个车型和标题同行的效果。 - 附加问题:税费计算逻辑错误,你在循环累加日租金时每次都乘1.06,相当于重复计税,正确逻辑应该是总租金累加完成后统一乘以税率。
修复方案
1. 修复车型数组赋值逻辑
删掉内层的j循环,直接给对应下标的vehicleRentedArry[i]赋值即可,修改后代码:
for(int i = 0; i < vehicleTypes.length; i++) { System.out.println("What vehicle type would you like? Motorbike, trailer, or car?: "); vehicleType = ReadStringFromUser(); if((vehicleType.equalsIgnoreCase("Motorbike")) || (vehicleType.equalsIgnoreCase("Trailer")) || (vehicleType.equalsIgnoreCase("Car"))) { vehicleTypes[i] = vehicleType; // 删掉内层j循环,直接给i下标赋值 if(vehicleType.equalsIgnoreCase("Motorbike")) { CMotorbike motorbikeOption = new CMotorbike(); motorbikeOption.SetMethods("Handle Bars", 35, 2); vehicleRentedArry[i] = motorbikeOption; }else if(vehicleType.equalsIgnoreCase("car")) { CCar carOption = new CCar(); carOption.SetMethods("Steering Wheel", 25, 4); vehicleRentedArry[i] = carOption; }else if(vehicleType.equalsIgnoreCase("Trailer")) { CTrailer trailerOption = new CTrailer(); trailerOption.SetMethods("Use Another Vehicle", 0, 6); vehicleRentedArry[i] = trailerOption; } } }
2. 修复税费计算逻辑
把税率计算移到循环外:
//Calculate the rates dailyRates = CalculateDailyRates(vehicleTypes, numOfVehicles, numOfDays); //Check if rates appear correctly for(int k = 0; k < dailyRates.length; k++) { totalRentalSale += dailyRates[k]; } // 总金额累加完成后统一计税 totalRentalSale = totalRentalSale *1.06f;
3. 修复打印格式逻辑
判断下标是否为0,首行不换行,后续行补缩进后换行:
//Printing the outputs: System.out.println("** Order Confirmation **"); System.out.printf("----------------------------------------------------------------------\n"); System.out.printf("Customer Name: \t\t\t\t%s %s\n", strFirstName, strLastName); System.out.printf("Phone Number: \t\t\t\t%s\n", strPhoneNumber); System.out.printf("Email: \t\t\t\t\t%s\n", strEmail); System.out.printf("----------------------------------------------------------------------\n"); System.out.println("** Details about Rental **"); System.out.printf("----------------------------------------------------------------------\n"); System.out.printf("Type of Vehicle: \t\t\t"); for(int intIndex = 0; intIndex < vehicleRentedArry.length; intIndex++) { String vehicleType = vehicleRentedArry[intIndex].getVehicleType(); if(intIndex == 0) { // 首辆车和标题同行 System.out.println(vehicleType); } else { // 后续车辆前面补对应缩进,再打印 System.out.printf("\t\t\t\t\t%s\n", vehicleType); } }
内容的提问来源于stack exchange,提问作者Brittney P
相关产品推荐
相关产品推荐

