如何基于其他元素参数更改数组列表中特定元素的特定参数

时间:2019-01-19 21:36:19

标签: java arraylist

我是Java新手,但是一直在使用数组列表,现在卡住了。

我从一个名为Car的类创建了一个数组列表,该数组具有三个参数,其中一个称为 times (移动次数)。

ArrayList:

 private ArrayList<Car> list = new ArrayList<Car>() ;

汽车课

 public Car ( String licenseNum, String carStatus , int timesMoved)
 {   
  licensePlate = licenseNum ;
  status = carStatus ;
  moved = timesMoved;
 }

我正在读取应该是车库的文件的输入,并说汽车是“到达” 还是“离开”

我正在尝试使用一条if语句编写代码,该语句表示状态为“正在离开”,则当前元素将被删除,其前面的所有元素都将添加到其“时间移动的参数”中

我停留的部分是根据删除的元素,将其在数组列表中位于其前面的所有元素添加到其“移动时间” 参数中的部分。< / p>

有人会给我一些建议吗?

我想出了这个,但似乎没有用

public void carDepart()
   {
     for ( int i = 0 ; i < list.size() ; i++ )
        {
         Car current = list.get( i ) ;   // get next car
            if (current.getStatus().equals("DEPART"))
            {
              int pos = list.indexOf(i);

                for ( int j = 0 ; pos < j ; j++)
                {
                 current.setTimesMoved(1 + current.getTimesMoved());
                }

                 list.remove(i);
          }
          break;
       }  
    }

第二种方法

    public void moveCarInGarage()
    {
      for ( int i = 0 ; i < list.size() ; i++ )
    {
       Car current = list.get( i ) ;     // get next car
       if (current.getStatus().equals("ARRIVE"))
     {
         currentCars++;

       if (currentCars <= 10) 
       {
           System.out.println("Car with license plate" + 
            current.getLicenseNum() + " has been moved into the garage");
       }
       else 
       {
           System.out.println("The garage is full at this " +
           "time so come back later");
       }
   }
     else 
     {
         currentCars--;
         System.out.println("Car with license plate" + 
           current.getLicenseNum() + " is departing and has been moved " 
                 + current.getTimesMoved() + " times" );
     }
  }

}

1 个答案:

答案 0 :(得分:3)

这是您可以做什么的一个示例。在其中,我假设您正在使用getter和setter。您还可以直接调用属性,前提是您已经设置了允许访问的修饰符。

我所做的就是创建一个名为增量时间增量移动()的新方法,该方法遍历您的ArrayList并递增其元素中的所有“移动”属性,直到到达具有给定索引的元素为止。它将删除它,并停止运行。

public class MCVE {

public static void main(String[] args) {
   // IMO list isn't very descriptive, so I changed it to carList.
   ArrayList<Car> carList = new ArrayList<>();

   // Add a bunch of values to carList here.

   for(int i = 0; i < carList.size(); i++) {
      if(carList.get(i).getStatus().equals("Departing")) {
         incrementTimesMoved(i, carList);
         return; // stops the method
      }
   }

}

// only static because I am calling in the main() function
private static void incrementTimesMoved(int index, ArrayList<Car> carList) {

   for(int i = 0; i < carList.size(); i++) {

      if(i == index) {
         carList.remove(index);
         return;
      }

      carList.get(i).setMoved(carList.get(i).getMoved() += 1);
   }
}

}