所以我已經為我預先編寫了這段代碼
public class Car
{
private String make;
private int yearModel;
private double price;
private int mileage;
public Car (String mk, int year, double pr, int miles)
{
make = mk;
yearModel = year;
price = pr;
mileage = miles;
}
public String getMake()
{
return make;
}
public int getYearModel()
{
return yearModel;
}
public double getPrice()
{
return price;
}
public int getMileage()
{
return mileage;
}
public String toString()
{
return "Make: " + make+"\n"+"YearModel: " + yearModel +"\n"+
"Price: $" + price +"\n" + "Mileage: "+ mileage + " miles\n\n";
}
}
我的任務是首先提示用戶輸入一個停車場的汽車數量。然後創建一個 Car 數組來保存輸入的汽車數量。然後用 carlot 上每輛車的信息填充數組。我知道一般概念,但是當我嘗試輸入一個字符串時,它表示與僅允許類型 Car 的數組 Cars 的類型不匹配。我很困惑那是什麼以及如何解決它。這是我的代碼。
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: ");
Car [] Cars = new Car [input.nextInt()];
for(int i = 0; i < Cars.length; i++) {
System.out.println("Make");
Cars[i] = input.nextLine();
System.out.println("Model");
Cars[i] = input.nextLine();
System.out.println("Price");
Cars[i] = input.nextLine();
System.out.println("Mileage");
Cars[i] = input.nextLine();
System.out.println();
}
input.close();
}
}
重要的是要注意Scanner
.nextLine()
不返回 a Car
,它返回 a String
。你需要Car
從輸入中提取出來。
所以在循環中你應該做這樣的事情(我將cars
變量名設為小寫以遵循 Java 命名約定):
System.out.println("Make");
String make = input.nextLine();
System.out.println("Model");
String model = input.nextLine();
System.out.println("Price");
double price = input.nextDouble();
System.out.println("Mileage");
int mileage = input.nextInt();
cars[i] = new Car(make, model, price, mileage);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句