我正在为我的CSCI 1301课程做这个作业,我有点卡住了。任务是编写一个程序,该程序将向用户提供服务列表,并允许他们选择他们想要的任何或所有服务并显示最终价格。这是我到目前为止的代码,
public static void carMaintenance()
{
Scanner sc = new Scanner(System.in);
String makeOfCar;
System.out.println("What's the make of your car?");
makeOfCar = sc.next();
String[] services = {"Oil Change", "Tire Rotation", "Air Filter", "Fluid Check"};
double[] prices = {39.99, 49.99, 19.99, 10.99};
System.out.println("What services whould you like for your "+makeOfCar+"?");
System.out.println(services[0]+", "+services[1]+", "+services[2]+", "+services[3]+".");
}
我陷入困境的是,我将如何允许用户请求他们想要的任意数量的服务?(从逻辑上讲,他们最多只能请求 4 个服务(
我想我可以使用另一个数组并将其放在"do-while"循环中来实现这一点,但是,一旦我根据"服务"数组检查它,我将如何为用户请求的每个服务分配价格,以便我可以计算所有请求服务的总价格?
任何见解和帮助将不胜感激!
您可以在额外的变量中跟踪总和。因此,您使用额外数组来检查重复项的想法仍然有效。检查是否已选择服务,如果没有,则将所选索引添加到总和中。
public static void carMaintenance() {
Scanner sc = new Scanner(System.in);
String makeOfCar;
System.out.println("What's the make of your car?");
makeOfCar = sc.nextLine();
String[] services = {"Oil Change", "Tire Rotation", "Air Filter", "Fluid Check"};
double[] prices = {39.99, 49.99, 19.99, 10.99};
double sum = 0;
System.out.println("What services whould you like for your " + makeOfCar + "?");
System.out.println(services[0] + ", " + services[1] + ", " + services[2] + ", " + services[3] + ".");
String choice;
//This array simply tracks true or false for chosen/not chosen. boolean arrays are initialized with all values false.
boolean[] chosenServices = new boolean[services.length]; //Can only be as many elements as there are services. This way you don't have to change it when you add another service
do {
choice = sc.nextLine();
int choiceIndex = getIndex(services, choice);
if (choiceIndex < 0) break; //Choice doesn't exist. You will have to refine that and add messages
if (!chosenServices[choiceIndex]) { //service not yet chosen
chosenServices[choiceIndex] = true;
sum += prices[choiceIndex];
} else {
System.out.println("Was already chosen!");
}
} while (!choice.toLowerCase().equals("exit")); //Or something similar
System.out.printf("%.2f", sum); //Price with 2 digits
}
public static int getIndex(String[] arr, String search) {
for (int i=0; i<arr.length; i++) {
if (search.equals(arr[i]))
return i;
}
return -1;
}
正如其中一条评论中提到的,这只是一个粗略的实现。您可能希望使用用户的索引输入来执行此操作,您可能希望检查比我在这里更精确的错误输入等,但这应该符合我认为您的意思。