gpt4 book ai didi

java - ArrayList 对象 (java)

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:21 26 4
gpt4 key购买 nike

我坚持逻辑,我的项目需要帮助。
我有一个包含 5 个车辆名称的文本文件。
然后我必须将它们读入一个 ArrayList,我使用的是:

public static void main(String[] args) throws IOException
{
BufferedReader bTextFileVehicleNames = new BufferedReader(new FileReader("vehicles.txt"));
ArrayList<String> vechicleNamesArray = new ArrayList<String>();
while((textFileLine = bTextFileVehicleNames.readLine()) != null)
{
vehicleNamesArray.add(textFileLine);
}

现在,我需要为 ArrayList 中的每个项目(车辆名称)创建一个对象,我使用的是:

for(String s : vehicleNamesArray)
{
newVehicle = new Vehicle(s);
//I defined this Vehicle newVehicle = null; in the main class. My main is also in the same Vehicle.java file.
}

这些对象中的每一个都有属性:poweranglespeed;和行为:powerOn()powerOff()SpeedUp()SlowDown() 等。这是我在 Vehicle 类中定义的。

现在,用户必须输入车辆名称命令。然后我将它们拆分并取 [0],这是车辆名称,必须首先检查它是否是 ArrayList 中的那些车辆名称之一(源自 txt文件),如果是,则必须将其引用到我在上面创建的特定对象。然后还要传入[1],这是对应对象特定行为的命令,可以是powerOnspeedUp等等等等。

for (int i=0; i< vehicleNamesArray.size(); i++)
{
if (vehicleNamesArray.get(i).matches(userVehicleName))
//userVehicleName is the [0] vehicle name entered by user
//userVehicleCommand is the [1] command entered by user
{
switch (userVehicleCommand.toLowerCase())
{
case "power on":
newVehicle.powerOn(); //calling that particular bahaviour of the object defined in Vehicle class.
System.out.println(newVehicle.getName()+" is powered ON.");
break;
...
...

例如,假设在 txt 中有 5 辆汽车(因此在 ArrayList 中),名称为:Audi、Bmw、Mercedez、Volkswagen、Porsche。问题是,无论我在车辆名称命令中输入什么,程序默认都会采用最后一个元素,在本例中是 ArrayList 中的 Porsche。即,当我说“Audi,powerON”时,它仍然打印出“Porsche is powered ON”。

我想我在链接用户输入的名称以检查 ArrayList 然后将其引用到该特定对象时搞砸了。

最佳答案

同时保留在 List 中创建的对象:

List<Vehicle> vehicleList = new ArrayList<>;
for(String s : vehicleNamesArray)
{
newVehicle = new Vehicle(s);
vehicleList.add(newVehicle);
//I defined this Vehicle newVehicle = null; in the main class. My main is also in the same Vehicle.java file.
}

然后在您的第二个 for 循环 中检索该车辆对象并更新它:

for (int i=0; i< vehicleNamesArray.size(); i++)
{
if (vehicleNamesArray.get(i).matches(userVehicleName))
//userVehicleName is the [0] vehicle name entered by user
//userVehicleCommand is the [1] command entered by user
{
switch (userVehicleCommand.toLowerCase())
{
case "power on":

vehicleList.get(i).powerOn(); //calling that particular bahaviour of the object defined in Vehicle class.
System.out.println(vehicleList.get(i).getName()+" is powered ON.");
break;
...
...

关于java - ArrayList 对象 (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30515779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com