首页 > 解决方案 > 类不能转换为字符串

问题描述

标题听起来很愚蠢,但听我说完

我正在尝试编写一个创建汽车(品牌、型号、生产年份和里程表)的程序,当我尝试将汽车添加到列表数组时,出现以下错误:

“不兼容的类型:汽车无法转换为字符串”

有谁知道解决这个问题的方法/解决这个问题的方法

任何帮助将不胜感激,我的代码如下(另外,我无法删除程序的 ArrayList 方面)。

public class Car {

    Scanner scan = new Scanner(System.in);

    ArrayList<String> cars = new ArrayList<String>(); 
    String make, model, year, odometer; 
    int ptr = 0;

    public Car(String year, String odometer, String make, String model) 
    { 
        this.make = make; 
        this.model = model; 
        this.year = year; 
        this.odometer = odometer; 
    } 

    public String toString() 
    { 
        return this.make + " " + this.model + " " + this.year+ " " + this.odometer; 
    } 

    public void carAdd(){
        System.out.println("What is the make of the car?");
        String newMake = scan.next();
        System.out.println("What is the model of the car?");
        String newModel = scan.next();
        System.out.println("What year was the car produced?");
        String newYear = scan.next();
        System.out.println("How far has this car traveled?");
        String newOdometer = scan.next();
        cars.add(new Car(newMake, newModel, newYear, newOdometer));
    }
}

标签: java

解决方案


您应该填充汽车列表,而不是字符串:

List<Car> cars = new ArrayList<>();

话虽如此,如果您真的想维护Car对象的字符串表示列表,那么您可以使用以下方法填充当前字符串列表Car#toString

public void carAdd(){
    System.out.println("What is the make of the car?");
    String newMake = scan.next();
    System.out.println("What is the model of the car?");
    String newModel = scan.next();
    System.out.println("What year was the car produced?");
    String newYear = scan.next();
    System.out.println("How far has this car traveled?");
    String newOdometer = scan.next();
    cars.add(new Car(newMake, newModel, newYear, newOdometer).toString());
}

您通常不会这样做,因为Car可以通过调用 轻松获得的字符串版本Car#toString。使用流,您可以尝试:

List<Car> cars = new ArrayList<>();
// populate list
List<String> carStrings = cars.stream()
    .map(c -> c.toString())
    .collect(Collectors.toList());

推荐阅读