對製作一個類的數組感到困惑

nbhat01

所以我已經為我預先編寫了這段代碼

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

對將數組推入數組感到困惑,JavaScript

對 Typescript 函數類型感到困惑

製作一個將一組數字之間的數字相加的函數

試圖用txt數據製作一個列表數組,Python

製作一個只對從控制台輸入的偶數求和的程序

如何在另一個類的對像中處理二維向量的數組?

帶有對象的循環數組我們在一個組件內有不同的類型

Pyspark:將數據幀作為數組類型列連接到另一個數據幀

按另一個對像數組對對像數組進行排序

做一個 2sum 算法,我對 python 語法感到困惑

對每個組應用一個函數

如何從元素數組製作對像數組

我如何在 django 模型上製作一個對我有用的計數器

將 Array<string> 類型轉換為一個對象,其中鍵是數組的字符串

對 getBoundingClientRect 感到困惑

對 Lambda 函數變量感到困惑

將對像數組轉換為一個對象的數組

將對像數組轉換為另一個對像數組

使用月對兩個對像數組進行聚類

如何從初始數組製作 2 個不同的混洗數組?javascript

React.jsx:類型無效——需要一個字符串(對於內置組件)或一個類/函數(對於復合組件)但得到:未定義

更新mongodb中對像數組的一個元素

Spring Boot - 返回一個空的對像數組

根據數組對像數據創建一個新數組

確定一個對像數組是否包含 JavaScript 中另一個數組的任何對象

JavaScript 查找:如果對象鍵存在於另一個對像數組中,則更新數組中對象的值,類似於 excel 中的 v-lookup

製作一個可管道化的函數

如何從每個都有一個列表作為字段的數據類對象列表中刪除重複項?

如何製作具有限制值的對像數組