jak kontrolować dodawane elementy to tablicy Array List?

0

Witam. Dopiero uczę się programowania Pracuje obecnie nad następującym ćwiczeniem:
//We are going to model a ship for transporting cars over the canal.

  • This ship has a maximum capacity of 100 places.
  • A second limitation is that the maximum weight that can be supported is 95000 kg.
    • We are going to model two kind of vehicles.
  • A car has a weight of 1000 kg and takes one place.
  • A van has a weight of 1500 kg and takes two places.
    • Create a class Ship.
    • Create the variables necessary to hold the information of the ship.
    • Write a method addVehicle(Vehicule aVehicule) to add a vehicule into the ship.
    • Write a method totalWeight() that returns the total weight of the content of the ship.
    • Write a method removeVehicle() to remove the last added vehicle
    • Write a method getContent() to check the content of the ship (return a String).
  • for example : "2500 kg and 25 places"
    • When adding or removing cars to your ship, pay attention to the maximum total number of cars and the maximum total weight.//

Do dodawania obiektów chce użyć ArrayList i wykorzystać metodę <add>. Jednakże nie wiem jak sobie poradzić ze sprawdzaniem czy tablica jest tuz pełna i jak ograniczyć dodawanie obiektów kiedy przekroczy capacity i weight. Będę bardzo wdzięczna za pomoc.

1

Zakładam, że informacje o załadowanych pojazdach przechowujesz w ArrayList<Vehicle> vehicles, przydatne będą też pola int places oraz int weight.

final int MAXIMUM_WEIGHT = 95000;
final int MAXIMUM_CAPACITY = 100;
boolean addVehicle(Vehicle vehicle){
    if(this.weigth + vehicle.weight > MAXIMUM_WEIGHT || this.places + vehicle.places > MAXIMUM_CAPACITY){
        return false;
    }
    else{
         vehicles.add(vehicle);
         this.weight+=vehicle.weight;
         this.places+=vehicle.places;
         return true;
    }
}
0

a po co w ogóle przechowywać to w liście? jedyne co masz zwracać z klasy to jego wagę i ilość zajętych miejsc. Nie ma sensu listy trzymać, wystarczy ostatni dodany element do metody removeVehicle

1

@IwettaSowa ArrayList jest słabym pomysłem ponieważ będzie trzeba trochę napisać dodatkowego kodu. Znacznie lepiej jest użyć do tego stosu https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html

Sprawa sprawdzania pozostałego miejsca tak jak opisał @bogdans - odpowiednia implementacja addVehicle, choć zrobiłbym to trochę inaczej wykorzystując dodatkową klasę sprawdzającą, a nie bezpośredniego ifa, ale to szczegół nie istotny na tym poziomie (technicznie masz możliwość budowania statków z konfigurowalnych komponentów).

0

@IwettaSowa, sumowanie wagi jak masz Stack:cargo można zrobić w taki sposób:

cargo.stream().mapToInt(Vehicle:getWeigth).sum();

stream tworzy strumień z kolekcji, mapToInt wyciąga informację o wadze i tworzy nowy strumień tym razem integerów, a sum sumuje całość.

1 użytkowników online, w tym zalogowanych: 0, gości: 1