创建Car类对象数组时遭遇类型不匹配问题,寻求解决方法
Hey there! Let's figure out what's causing your type mismatch error and fix it up properly.
Why You're Getting the Error
Your Cars array is explicitly declared as a Car type array (Car [] Cars = new Car [input.nextInt()]). That means every element in this array must be a fully initialized Car object. Right now, you're trying to assign raw strings from input.nextLine() directly to Cars[i]—this is like trying to put a book into a shelf meant for potted plants; the types don't match at all, hence the compiler error.
On top of that, there's a hidden issue with input.nextInt(): it only reads the numeric value you enter, leaving the newline character (\n) in the input buffer. The first input.nextLine() will read this empty newline instead of your intended input, causing your prompts to get out of sync.
How to Fix It
We need to adjust your code to:
- Clear the leftover newline after using
nextInt() - Read all required values for a car first, then create a
Carobject with those values, and finally assign that object to the array
Here's the corrected CarLot code with comments explaining the key changes:
import java.util.Scanner; public class CarLot { public static void main (String [] args) { Scanner input = new Scanner(System.in); System.out.println("Input number of cars: "); int carCount = input.nextInt(); // Fix: Clear the newline left by nextInt() input.nextLine(); Car [] Cars = new Car [carCount]; for(int i = 0; i < Cars.length; i++) { System.out.println("Enter details for Car #" + (i+1) + ":"); // Read all individual properties first System.out.print("Make: "); String make = input.nextLine(); System.out.print("Year Model: "); int yearModel = Integer.parseInt(input.nextLine()); System.out.print("Price: "); double price = Double.parseDouble(input.nextLine()); System.out.print("Mileage: "); int mileage = Integer.parseInt(input.nextLine()); // Fix: Create a Car object with the collected values and assign to the array Cars[i] = new Car(make, yearModel, price, mileage); System.out.println(); } // Optional: Test printing all cars to verify System.out.println("All cars in the lot:"); for(Car car : Cars) { System.out.println(car); } input.close(); } }
Key Notes:
- We use
Integer.parseInt()andDouble.parseDouble()to convert the input strings into the numeric types required by theCarconstructor. - By creating a
Carobject with the collected values, we're properly assigning a matching type to the array element. - The
input.nextLine()afternextInt()ensures we don't accidentally read an empty line for the first car's make.
内容的提问来源于stack exchange,提问作者nbhat01

