java - 类不能转换为字符串
问题描述
标题听起来很愚蠢,但听我说完
我正在尝试编写一个创建汽车(品牌、型号、生产年份和里程表)的程序,当我尝试将汽车添加到列表数组时,出现以下错误:
“不兼容的类型:汽车无法转换为字符串”
有谁知道解决这个问题的方法/解决这个问题的方法
任何帮助将不胜感激,我的代码如下(另外,我无法删除程序的 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));
}
}
解决方案
您应该填充汽车列表,而不是字符串:
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());
推荐阅读
- cuda - 如何在具有计算能力 7.x 的 CUDA 应用程序中进行分析?度量标准“dram_read_throughput”在 Nsight Compute 中有效吗?
- activemq-artemis - 为 ActiveMQ Artemis 中的特定记录器启用 TRACE
- python - 尝试向 API 发送 POST 请求时出现属性错误 - Django
- python - 在 Django 中,如何根据屏幕大小加载图像?
- r - 使用 ggplot2 将带有文本的图像作为刻度标签
- python - Pyodbc - 无效的连接字符串 - 用户登录失败
- django - ModelChoiceField:删除空选项并选择默认值
- javascript - 仅在每次点击时使用 jquery 或 javascript 打开一级深层子菜单
- wordpress - 如何在 WooCommerce 中针对全国不同地区组织不同的运费和运费方式?
- javascript - 如何测试 TOML 文件中的“0”和“假”?