samedi 19 janvier 2019

Incrementing ArrayElement Parameters based on previous ELEMENTS

I am new to java but have been playing with array-lists and am now stuck.

I have an array list created off a class called Car with three parameters one of which is called times moved.

ArrayList:

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

Car class

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

I am reading input of a file that is supposed to be like a garage and says if a car is "Arriving" or "Departing"

I am trying to write a code using an if statement that says if the status is "Departing" then the current element gets deleted the all elements in front of it add one to their "times moved parameter"

The part I am stuck on is the one where, based on the element getting deleted, all the elements in front of it in the array list add one to their "times moved" parameter.

I came up with this but it does not seem to work as when I call the 2nd method it always says 0 for times moved.

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);
                 return;
          }

       }  
    }

Second method

    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" );
     }
  }

}

Aucun commentaire:

Enregistrer un commentaire