CSCI 1301作业求助:实现用户任意输入字符串匹配数组及服务选择
Hey there! Let's break down how to tackle this CSCI 1301 assignment step by step. From what you've shared, you need to build a program that shows a service list, lets users pick multiple services to calculate the total cost, and also handle string input to match against your services array. Let's fill in the gaps in your code and make it work as required.
Since you need to calculate a final total, you'll want to link each service to its cost. For a beginner-friendly approach (perfect for CSCI 1301), use parallel arrays—one for service names, one for corresponding prices:
String[] services = {"Oil Change", "Tire Rotation", "Air Filter", "Brake Inspection", "Battery Replacement"}; double[] prices = {29.99, 49.99, 19.99, 39.99, 89.99};
Users need to see what's available, so print the list with numbered options (makes selection easier):
// Show available services to the user System.out.println("\nAvailable Maintenance Services:"); for (int i = 0; i < services.length; i++) { System.out.printf("%d. %s - $%.2f%n", (i + 1), services[i], prices[i]); }
Let users pick as many services as they want, and validate their input (whether they type a service number or the full name). We'll loop until they type "done" to finish:
double totalCost = 0.0; sc.nextLine(); // Fixes the leftover newline issue from sc.next() System.out.println("\nEnter the number or name of each service you want (type 'done' when finished):"); while (true) { String input = sc.nextLine().trim(); // Exit loop when user is done if (input.equalsIgnoreCase("done")) { break; } // First, try to parse input as a service number try { int choice = Integer.parseInt(input) - 1; // Convert to 0-based array index if (choice >= 0 && choice < services.length) { totalCost += prices[choice]; System.out.printf("Added %s to your list.%n", services[choice]); } else { System.out.println("That's not a valid service number. Try again."); } } catch (NumberFormatException e) { // If input isn't a number, check if it matches a service name boolean serviceFound = false; for (int i = 0; i < services.length; i++) { if (services[i].equalsIgnoreCase(input)) { totalCost += prices[i]; System.out.printf("Added %s to your list.%n", services[i]); serviceFound = true; break; } } if (!serviceFound) { System.out.println("That's not a valid service name or number. Try again."); } } }
Wrap up by printing the total cost for the user's car:
System.out.printf("%nYour total maintenance cost for your %s is: $%.2f%n", makeOfCar, totalCost); sc.close();
Putting it all together, here's the complete carMaintenance() method and a main method to run it:
import java.util.Scanner; public class CarMaintenanceApp { public static void carMaintenance() { Scanner sc = new Scanner(System.in); // Get car make from user String makeOfCar; System.out.println("What's the make of your car?"); makeOfCar = sc.next(); System.out.printf("Got it, let's look at services for your %s.%n", makeOfCar); // Define services and their prices String[] services = {"Oil Change", "Tire Rotation", "Air Filter", "Brake Inspection", "Battery Replacement"}; double[] prices = {29.99, 49.99, 19.99, 39.99, 89.99}; // Display service list System.out.println("\nAvailable Maintenance Services:"); for (int i = 0; i < services.length; i++) { System.out.printf("%d. %s - $%.2f%n", (i + 1), services[i], prices[i]); } // Handle service selection double totalCost = 0.0; sc.nextLine(); // Consume leftover newline from sc.next() System.out.println("\nEnter the number or name of each service you want (type 'done' when finished):"); while (true) { String input = sc.nextLine().trim(); if (input.equalsIgnoreCase("done")) { break; } try { int choice = Integer.parseInt(input) - 1; if (choice >= 0 && choice < services.length) { totalCost += prices[choice]; System.out.printf("Added %s to your list.%n", services[choice]); } else { System.out.println("Invalid service number. Try again."); } } catch (NumberFormatException e) { boolean serviceFound = false; for (int i = 0; i < services.length; i++) { if (services[i].equalsIgnoreCase(input)) { totalCost += prices[i]; System.out.printf("Added %s to your list.%n", services[i]); serviceFound = true; break; } } if (!serviceFound) { System.out.println("Invalid service name or number. Try again."); } } } // Show final total System.out.printf("%nYour total maintenance cost for your %s is: $%.2f%n", makeOfCar, totalCost); sc.close(); } public static void main(String[] args) { carMaintenance(); } }
- Input Fix: The
sc.nextLine()aftersc.next()solves a common scanner bug where the first user input after the car make gets skipped. - Flexible Matching: Users can select services by number or name, which meets your requirement to match user input to the array.
- Error Handling: The try-catch and loop validation ensure the program doesn't crash from bad input.
内容的提问来源于stack exchange,提问作者marc30599

